The best way to calculate the height in a binary search tree? (balancing an AVL-tree)

前端 未结 9 741
渐次进展
渐次进展 2020-12-12 10:39

I\'m looking for the best way to calculate a nodes balance in an AVL-tree. I thought I had it working, but after some heavy inserting/updating I can see that it\'s not worki

9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-12 11:00

    Part 1 - height

    As starblue says, height is just recursive. In pseudo-code:

    height(node) = max(height(node.L), height(node.R)) + 1
    

    Now height could be defined in two ways. It could be the number of nodes in the path from the root to that node, or it could be the number of links. According to the page you referenced, the most common definition is for the number of links. In which case the complete pseudo code would be:

    height(node): 
       if node == null:
            return -1
       else:
            return max(height(node.L), height(node.R)) + 1
    

    If you wanted the number of nodes the code would be:

    height(node): 
       if node == null:
            return 0
       else:
            return max(height(node.L), height(node.R)) + 1
    

    Either way, the rebalancing algorithm I think should work the same.

    However, your tree will be much more efficient (O(ln(n))) if you store and update height information in the tree, rather than calculating it each time. (O(n))

    Part 2 - balancing

    When it says "If the balance factor of R is 1", it is talking about the balance factor of the right branch, when the balance factor at the top is 2. It is telling you how to choose whether to do a single rotation or a double rotation. In (python like) Pseudo-code:

    if balance factor(top) = 2: // right is imbalanced
         if balance factor(R) = 1: // 
              do a left rotation
         else if balance factor(R) = -1:
              do a double rotation
    else: // must be -2, left is imbalanced
         if balance factor(L) = 1: // 
              do a left rotation
         else if balance factor(L) = -1:
              do a double rotation
    

    I hope this makes sense

提交回复
热议问题