#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.
思路:寻找每个节点的子树的高度,也就是需要一个获取树高度的方法。这里可以遍历的时候顺便计数,当差值大于1的时候就直接跳出循环,减少不必要的运算。
//求root节点的高度的方法,其高度等于左子树与右子树较高者+1
int height(TreeNode *root){
if (root == NULL)return 0;
int lh = height(root->left);
int rh = height(root->right);
if (lh > rh)return lh + 1;
else return rh + 1;
}
Java Solution
public class Solution {
public boolean isBalanced(TreeNode root) {
return getBalancedHeight(root)!=-1;
}
public int getBalancedHeight(TreeNode root){
if(root==null) return 0;
int leftH = getBalancedHeight(root.left);
if(leftH<0)return -1;
int rightH= getBalancedHeight(root.right);
if(rightH<0)return -1;
if(Math.abs(leftH-rightH)>1)return -1;
return Math.max(leftH,rightH)+1;
}
}