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即可。
public class Solution {
boolean result = true;
private int helper(TreeNode root){
if(root == null) return 0;
int leftDepth = helper(root.left);
int rightDepth = helper(root.right);
if(Math.abs(leftDepth-rightDepth) >1) {
result = false;
}
return Math.max(leftDepth, rightDepth)+1;
}
public boolean isBalanced(TreeNode root) {
helper(root);
return result;
}
}
时间复杂度为O(N),空间复杂度为O(H)。