Wednesday, January 14, 2015

Balanced Binary Tree (LeetCode Tree)

Question: 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.

Idea: Since the height of a tree is always non-negative, we can use the negative numbers to deliver a message as "this is not a balanced substree" when getting the height. So the algorithm is:
1) Get the height of the tree recursively
2) If the current substree is balanced, return the height;
3) If the current substree is not balanced, return -1. This -1 will be transferred all the way to the root of the tree level by level.

Time: O(n) Space: O(n)

Code:
 public class Solution {  
   public int getHeight(TreeNode root)  
   {  
     if(root==null)  
       return 0;  
     int left=getHeight(root.left);  
     int right=getHeight(root.right);  
     if(left==-1||right==-1||Math.abs(left-right)>1)  
       return -1;  
     return Math.max(left,right)+1;  
   }  
   public boolean isBalanced(TreeNode root) {  
     return getHeight(root)!=-1;  
   }  
 }  

No comments:

Post a Comment