美文网首页
Tree Basics

Tree Basics

作者: SharlotteZZZ | 来源:发表于2018-11-07 23:26 被阅读0次

    BST: all left <= n < all right

    How to determine if a binary tree is height-balanced?
    An empty tree is height-balanced. A non-empty binary tree T is balanced if:

    1. Left subtree of T is balanced
    2. Right subtree of T is balanced
    3. The difference between heights of left subtree and right subtree is not more than 1.
    def isBalanced(root): 
      
        if root is None: 
            return True
      
        # for left and right subtree height 
        lh = height(root.left) 
        rh = height(root.right) 
      
        #  (lh - rh) could be 1, -1, 0 
        if (abs(lh - rh) <= 1) and isBalanced( 
        root.left) and isBalanced( root.right): 
            return True
     
        return False
    

    Balanced tree: red-black trees and AVL trees

    A complete binary tree is a binary tree in which every level of the tree is fully filled, except for perhaps the last level. To the extent that the last level is filled, it is filled left to right.

    A full binary tree is a binary tree in which every node has either zero or two children. That is, no nodes have only one child.

    A perfect binary tree is one that is both full and complete. All leaf nodes will be at the same level, and this level has the maximum number of nodes.

    相关文章

      网友评论

          本文标题:Tree Basics

          本文链接:https://www.haomeiwen.com/subject/zmvvzftx.html