Given a binary tree, determine if it is
public class Solution {
public boolean NotBalancedflag;
public boolean isBalanced(TreeNode root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
NotBalancedflag = false;
checkBalanced(root);
if (NotBalancedflag)
return false;
else
return true;
}
public int checkBalanced(TreeNode root) {
if (NotBalancedflag == true)
return -1;
if (root == null)
return 0;
int leftDepth = checkBalanced(root.left);
int rightDepth = checkBalanced(root.right);
if (java.lang.Math.abs(leftDepth - rightDepth) > 1) {
NotBalancedflag = true;
}
return java.lang.Math.max(leftDepth, rightDepth) + 1;
}
}
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.