Leetcode-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.
Solution:
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public boolean isBalanced(TreeNode root) { 12 if (root==null) 13 return true; 14 15 int depth = isBalancedRecur(root); 16 if (depth==-1) 17 return false; 18 else 19 return true; 20 21 } 22 23 public int isBalancedRecur(TreeNode curNode){ 24 if (curNode.left==null&&curNode.right==null) 25 return 1; 26 27 int left=0; 28 int right=0; 29 if (curNode.left!=null) 30 left = isBalancedRecur(curNode.left); 31 if (left==-1) 32 return -1; 33 if (curNode.right!=null) 34 right = isBalancedRecur(curNode.right); 35 if (right==-1) 36 return -1; 37 38 if (left-right>1 || left-right<-1) 39 return -1; 40 else { 41 if (left>right) 42 return left+1; 43 else 44 return right+1; 45 } 46 47 } 48 }
This is a recursive problem. Get the depth of the left child tree and the right child tree, if they are not balanced, then return -1 to indicate that unbalance is found. If get -1 from any of the two child trees, then return -1 immediately.