先介绍一个概念:
Height balance property: For every internal node v of T, the height of the children of v differs by 1 at most. 每个子结点的高度差最多为1.
符合Height balance property的BST叫做AVL Tree,平衡二叉树。
对于一个有n个节点的平衡二叉树来说,它的高度是O(logn),证明参考:点击打开链接
AVL的插入操作与BST的插入操作相似,之后还要再进行一步判断Tree 是否达到平衡。这里引入函数getBalance返回左右子节点的高度差。设Z是我们判断的对象,y是z在插入路径上的子节点,x是插入路径上的孙子节点。判断的结果通常为以下4种:
- left left case : we need to right rotate the tree for once
- left right case: First, we need to right rotate the tree, then to left rotate the tree
- right right case : we need to left rotate the tree for once
- right left case: First, we need to left rotate the tree, then to right rotate the tree
insert()方法