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 everynode never differ by more than 1.
[解题思路]
检查每个node是否是balanced,大数据集挂掉了
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 // Start typing your Java solution below 13 // DO NOT write main() function 14 if(root == null){ 15 return true; 16 } 17 18 return checkBalance(root); 19 } 20 21 public boolean checkBalance(TreeNode node){ 22 if(node == null){ 23 return true; 24 } 25 int left = getDepth(node.left); 26 int right = getDepth(node.right); 27 if(Math.abs(left - right) > 1){ 28 return false; 29 } 30 return checkBalance(node.left) && checkBalance(node.right); 31 } 32 33 public int getDepth(TreeNode node){ 34 if(node == null){ 35 return 0; 36 } 37 int left = getDepth(node.left); 38 int right = getDepth(node.right); 39 return Math.max(left, right) + 1; 40 } 41 }