Given a binary tree, determine if it is height-balanced.
a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
// Definition for a binary tree node.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
/**
* Time complexity :
* Space complexity :
*/
class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
if(Math.abs(height(root.left)-height(root.right)) > 1) {
return false;
}
return isBalanced(root.left) && isBalanced(root.right);
}
private int height(TreeNode root) {
if(root == null) return 0;
return 1 + Math.max(height(root.left), height(root.right));
}
}
/**
* Time complexity :
* Space complexity :
*/
class Solution {
private int diff = 0;
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
height(root);
return diff <= 1;
}
private int height(TreeNode root) {
if(root == null) return 0;
int lh = height(root.left);
int rh = height(root.right);
diff = Math.max(diff, Math.abs(lh-rh));
return 1 + Math.max(lh, rh);
}
}