How to determine if binary tree is balanced?

前端 未结 27 1473
萌比男神i
萌比男神i 2020-11-30 16:11

It\'s been a while from those school years. Got a job as IT specialist at a hospital. Trying to move to do some actual programming now. I\'m working on binary trees now, a

相关标签:
27条回答
  • 2020-11-30 16:53

    Bonus exercise response. The simple solution. Obviously in a real implementation one might wrap this or something to avoid requiring the user to include height in their response.

    IsHeightBalanced(tree, out height)
        if (tree is empty)
            height = 0
            return true
        balance = IsHeightBalanced(tree.left, heightleft) and IsHeightBalanced(tree.right, heightright)
        height = max(heightleft, heightright)+1
        return balance and abs(heightleft - heightright) <= 1     
    
    0 讨论(0)
  • 2020-11-30 16:53

    Well, you need a way to determine the heights of left and right, and if left and right are balanced.

    And I'd just return height(node->left) == height(node->right);

    As to writing a height function, read: Understanding recursion

    0 讨论(0)
  • 2020-11-30 16:55
    class Node {
        int data;
        Node left;
        Node right;
    
        // assign variable with constructor
        public Node(int data) {
            this.data = data;
        }
    }
    
    public class BinaryTree {
    
        Node root;
    
        // get max depth
        public static int maxDepth(Node node) {
            if (node == null)
                return 0;
    
            return 1 + Math.max(maxDepth(node.left), maxDepth(node.right));
        }
    
        // get min depth
        public static int minDepth(Node node) {
            if (node == null)
                return 0;
    
            return 1 + Math.min(minDepth(node.left), minDepth(node.right));
        }
    
        // return max-min<=1 to check if tree balanced
        public boolean isBalanced(Node node) {
    
            if (Math.abs(maxDepth(node) - minDepth(node)) <= 1)
                return true;
    
            return false;
        }
    
        public static void main(String... strings) {
            BinaryTree tree = new BinaryTree();
            tree.root = new Node(1);
            tree.root.left = new Node(2);
            tree.root.right = new Node(3);
    
    
            if (tree.isBalanced(tree.root))
                System.out.println("Tree is balanced");
            else
                System.out.println("Tree is not balanced");
        }
    }
    
    0 讨论(0)
  • 2020-11-30 17:01

    The definition of a height-balanced binary tree is:

    Binary tree in which the height of the two subtrees of every node never differ by more than 1.

    So, An empty binary tree is always height-balanced.
    A non-empty binary tree is height-balanced if:

    1. Its left subtree is height-balanced.
    2. Its right subtree is height-balanced.
    3. The difference between heights of left & right subtree is not greater than 1.

    Consider the tree:

        A
         \ 
          B
         / \
        C   D
    

    As seen the left subtree of A is height-balanced (as it is empty) and so is its right subtree. But still the tree is not height-balanced as condition 3 is not met as height of left-subtree is 0 and height of right sub-tree is 2.

    Also the following tree is not height balanced even though the height of left and right sub-tree are equal. Your existing code will return true for it.

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

    So the word every in the def is very important.

    This will work:

    int height(treeNodePtr root) {
            return (!root) ? 0: 1 + MAX(height(root->left),height(root->right));
    }
    
    bool isHeightBalanced(treeNodePtr root) {
            return (root == NULL) ||
                    (isHeightBalanced(root->left) &&
                    isHeightBalanced(root->right) &&
                    abs(height(root->left) - height(root->right)) <=1);
    }
    

    Ideone Link

    0 讨论(0)
  • 2020-11-30 17:01

    Note 1: The height of any sub-tree is computed only once.

    Note 2: If the left sub-tree is unbalanced then the computation of the right sub-tree, potentially containing million elements, is skipped.

    // return height of tree rooted at "tn" if, and only if, it is a balanced subtree
    // else return -1
    int maxHeight( TreeNode const * tn ) {
        if( tn ) {
            int const lh = maxHeight( tn->left );
            if( lh == -1 ) return -1;
            int const rh = maxHeight( tn->right );
            if( rh == -1 ) return -1;
            if( abs( lh - rh ) > 1 ) return -1;
            return 1 + max( lh, rh );
        }
        return 0;
    }
    
    bool isBalanced( TreeNode const * root ) {
        // Unless the maxHeight is -1, the subtree under "root" is balanced
        return maxHeight( root ) != -1;
    }
    
    0 讨论(0)
  • 2020-11-30 17:01

    If this is for your job, I suggest:

    1. do not reinvent the wheel and
    2. use/buy COTS instead of fiddling with bits.
    3. Save your time/energy for solving business problems.
    0 讨论(0)
提交回复
热议问题