multiple AVL tree rotation

泄露秘密 提交于 2019-12-11 06:49:58

问题


Say i have a unordered set s{3,6,5,1,2,4} and i need to construct an AVL tree,
this much is fine... i understand basic rotations and i get to this point here:

                               5 
                             /   \
                            2      6
                           / \
                         1     3

but it all falls apart when i try to insert 4 and i get my final answer as (the left one)

             4      But the actual answer is:      3
           /   \                                 /   \
          2     5                               2     5
         / \     \                             /     / \
        1   3     6                           1     4   6

And when i break it down i get stuck doing the same rotation
so im asking how do i do a rotation with the parent that is valid for this AVL?

and is my solution valid?


回答1:


Well, as I understand it, when you first add 4 you get the following tree.

    5
   / \
  2   6
 / \
1   3
     \
      4

To follow along, refer to Wikipedia's article on AVL trees. Because the balance factor (note that this is defined in the article) of node 5 is +2 and the balance factor of node 2 is -1, you first need to rotate the node 2 subtree left.

      5
     / \
    3   6
   / \
  2   4
 /
1

Next, you need to rotate the entire tree right (about node 5).

    3
   / \
  2   5
 /   / \
1   4   6

Does that make sense?



来源:https://stackoverflow.com/questions/6323656/multiple-avl-tree-rotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!