二叉查找平衡樹---再平衡旋轉

public class AvlTree {

public AvlTree() {

}

public static class AvlNode {
	int val;
	AvlNode left;
	AvlNode right;
	int height;

	AvlNode(int e) {
		val = e;
	}

	AvlNode(int e, AvlNode l, AvlNode r) {
		val = e;
		left = l;
		right = r;
		height = 0;
	}
}

public int getHeight(AvlNode node) {
	return node != null ? node.height : -1;
}

private AvlNode insert(int e, AvlNode t) {
	if (t == null) {
		return new AvlNode(e, null, null);
	}
	if (e < t.val) {
		t.left = insert(e, t.left);// insert to left child
		if (getHeight(t.left) - getHeight(t.right) == 2) {// have excel
			if (e < t.left.val) {
				t = rotateWithLeftChild(t);
			} else {
				t = doubleWithLeftChild(t);
			}
		}

	} else if (e > t.val) {
		t.right = insert(e, t.right);
		if (getHeight(t.right) - getHeight(t.left) == 2) {
			if (e > t.right.val) {
				t = rotateWithRightChild(t);
			} else {
				t = doubleWithRightChild(t);
			}
		}
	}
	t.height = Math.max(getHeight(t.left), getHeight(t.right)) + 1;
	return t;
}

private AvlNode rotateWithRightChild(AvlNode node) {
	AvlNode k1 = node.right;// k1是中間節點,最後返回k1
	node.right = k1.left;
	k1.left = node;
	node.height = Math.max(getHeight(node.left), getHeight(node.right)) + 1;
	k1.height = Math.max(getHeight(k1.right), getHeight(k1.left)) + 1;
	return k1;
}

private AvlNode rotateWithLeftChild(AvlNode k2) {
	AvlNode k1 = k2.left;
	k2.left = k1.right;
	k1.right = k2;
	k2.height = Math.max(getHeight(k2.left), getHeight(k2.right)) + 1;
	k1.height = Math.max(getHeight(k1.right), getHeight(k1.left)) + 1;
	return k1;
}

public AvlNode doubleWithLeftChild(AvlNode k3) {
	k3.left = rotateWithRightChild(k3.left);
	return rotateWithLeftChild(k3);
}

public AvlNode doubleWithRightChild(AvlNode k3) {
	k3.right = rotateWithLeftChild(k3.right);
	return rotateWithRightChild(k3);
}

public void firstRetrival(AvlNode root) {
	if(root == null) return;
	if (root.left != null) {
		firstRetrival(root.left);
	}
	System.out.println("" + root.val);
	if (root.right != null) {
		firstRetrival(root.right);
	}
}

public static void main(String[] args) {
	AvlTree tree = new AvlTree();
	AvlNode root = tree.insert(0, null);
	root = tree.insert(3, root);
	root = tree.insert(4, root);
	root = tree.insert(9, root);
	root = tree.insert(23, root);
	root = tree.insert(6, root);
	tree.firstRetrival(root);
	root = tree.insert(5, root);//
}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章