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:
public class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
if (Math.abs(maxdeep(root.left) - maxdeep(root.right)) > 1) return false;
return isBalanced(root.left)&&isBalanced(root.right);
}
public int maxdeep(TreeNode root){
if (root == null) return 0;
return Math.max(maxdeep(root.left), maxdeep(root.right)) + 1;
}
}
Time Complexity: O(n^2)
Solution 2:
public class Solution {
public boolean isBalanced(TreeNode root) {
return BackOrderT(root) > -1;
}
public int BackOrderT(TreeNode root){
if (root == null) return 0;
int leftDep = BackOrderT(root.left);
int rightDep = BackOrderT(root.right);
if ( (Math.abs(leftDep - rightDep) > 1)||(leftDep == -1)||(rightDep == -1) ) return -1;
return Math.max(leftDep + 1, rightDep + 1);
}
}
Time Complexity: O(n)