110. Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
    3
   / \
  9  20
    /  \
   15   7
Return true.

Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]:
       1
      / \
     2   2
    / \
   3   3
  / \
 4   4
Return false.
Solution:
Top down
Depth(Height): the distance from the leaf. if the node is null, return 0. Not the level which is the distance from the root.
isBalance: 
1) left subtree is balanced
2) right subtree is balanced.
3) the different between the height of  left subtree and right subtree is not more than 1.

class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null) return true;
        int leftDepth = depth(root.left);
        int rightDepth = depth(root.right);
        return ((Math.abs(leftDepth- rightDepth) <=1)
                && isBalanced(root.left)
                && isBalanced(root.right));
    }
    
    public int depth(TreeNode node){
        if(node == null) return 0;
        return 1 + Math.max(depth(node.left),depth(node.right));
    }
}

Optimized implementation:
Bottom Up.
1) merge isBalanced and depth, both return depth and boolean isBalanced.
2) if the tree is not balanced, return -1;
     if the tree is balanced, return height;
class Solution {
    public boolean isBalanced(TreeNode root) {
        if(isBalancedWithHeight(root) == -1) return false;
        else return true;
    }
    
    public int isBalancedWithHeight(TreeNode root){
        if(root == null) return 0;
        int lh = isBalancedWithHeight(root.left);
        if(lh == -1) return -1;
        int rh = isBalancedWithHeight(root.right);
        if(rh == -1) return -1;
        if(Math.abs(lh-rh) > 1){
            return -1;
        }else{
            return 1 + Math.max(rh,lh);
        }
        
    }
}



Comments

Popular posts from this blog

MockInterview:785. Is Graph Bipartite?

geeksforgeeks:findFind zeroes to be flipped so that number of consecutive 1’s is maximized

94.Binary Tree Inorder Traversal