2018.5.2
平衡二叉树(AVL Tree)是任意结点平衡因子BF(左右子树左右高度差)≤1的二叉搜索树。要想建成AVL树,需要在每一个结点插入时进行判断和调整。调整的方法有四种(左左单旋、右右单旋、左右双旋、右左双旋),四种方式分别根据结点插入时的相对结构判断,如下图Figure1的情况为左左单旋调整情况。
本题要求根据输入顺序建一棵AVL树,并且返回其根节点。思路就是AVL树的基本操作了。需要注意的是,给树的每个结点加一个参数代表树高,当左右子树高度差为2时进行调整,每次对树结构调整后也需要对树高值进行调整。具体操作详见代码。
Root of AVL Tree
An AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. Figures 1-4 illustrate the rotation rules.
Now given a sequence of insertions, you are supposed to tell the root of the resulting AVL tree.