Avl树即左右子树的深度【高度】相差不可超过1,所以在插入key的时候,就会出现需要旋转【更改根节点】的操作
下面是源代码:
/* the define of avltree's node */ class MyNode { int key, height; MyNode left, right; MyNode(int d) { key = d; height = 1; } } public class MyAvlTree { MyNode root; /* the function of get_tree_height */ int getHeight(MyNode node) { if (node == null) return 0; return node.height; } /* the function of get the max of two numbers */ int max(int a, int b) { return (a > b) ? a : b; } /* the function of right rotate subtree rooted y */ MyNode rightRoate(MyNode y) { MyNode x = y.left; MyNode t = x.right; /* perform rotation */ x.right = y; y.left = t; /* update the heights */ y.height = max(getHeight(y.left), getHeight(y.right)) + 1; x.height = max(getHeight(x.left), getHeight(x.right)) + 1; // return new root return x; } /* the function of left rotate subtree rooted x */ MyNode leftRoate(MyNode x) { MyNode y = x.right; MyNode t = y.left; /* perform rotation */ y.left = x; x.right = t; /* update the heights */ x.height = max(getHeight(x.left), getHeight(x.right)); y.height = max(getHeight(y.left), getHeight(y.right)); //return new root return x; } /* get balance factor of node n */ int getBalance(MyNode node) { if (node == null) return 0; return getHeight(node.left) - getHeight(node.right); } /* the function of insert */ MyNode insertKey(MyNode n, int key) { if (n == null) return (new MyNode(key)); if (key > n.key) n.right = insertKey(n.right, key); else if (key < n.key) n.left = insertKey(n.left, key); else return n; /* update height */ n.height = 1 + max(getHeight(n.left), getHeight(n.right)); //get balance int balance = getBalance(n); /* there are four cases */ //left-left case if (balance > 1 && key < n.left.key) return rightRoate(n); //right-right case if (balance > 1 && key > n.right.key) return leftRoate(n); //left-right case if (balance > 1 && key > n.left.key) { n.left = leftRoate(n.left); return rightRoate(n); } //right-left case if (balance > 1 && key < n.right.key) { n.right = rightRoate(n.right); return leftRoate(n); } return n; } /* the functionn of preOrder */ void preOrder(MyNode node) { if (node != null) { System.out.print(node.key + " "); preOrder(node.left); preOrder(node.right); } } /* the test example */ public static void main(String[] args) { MyAvlTree tree = new MyAvlTree(); //the test tree.root = tree.insertKey(tree.root, 10); tree.root = tree.insertKey(tree.root, 20); tree.root = tree.insertKey(tree.root, 30); tree.root = tree.insertKey(tree.root, 40); tree.root = tree.insertKey(tree.root, 50); tree.root = tree.insertKey(tree.root, 25); System.out.println("Preorder traversal" + " of constructed tree is : "); tree.preOrder(tree.root); } }