Definition of a Balanced Tree

后端 未结 6 912
暖寄归人
暖寄归人 2020-12-04 05:38

I am just wondering if someone might be able to clarify the definition of a balanced tree for me. I have that \"a tree is balanced if each sub-tree is balanced and the heigh

6条回答
  •  旧时难觅i
    2020-12-04 06:12

    The constraint is generally applied recursively to every subtree. That is, the tree is only balanced if:

    1. The left and right subtrees' heights differ by at most one, AND
    2. The left subtree is balanced, AND
    3. The right subtree is balanced

    According to this, the next tree is balanced:

         A
       /   \
      B     C  
     /     / \  
    D     E   F  
         /  
        G  
    

    The next one is not balanced because the subtrees of C differ by 2 in their height:

         A
       /   \
      B     C   <-- difference = 2
     /     /
    D     E  
         /  
        G  
    

    That said, the specific constraint of the first point depends on the type of tree. The one listed above is the typical for AVL trees.

    Red-black trees, for instance, impose a softer constraint.

提交回复
热议问题