Given a binary tree, determine if it is height-balanced.
https://leetcode.com/problems/balanced-binary-tree/
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: true
Example 2:
Input: root = [1,2,2,3,3,null,null,4,4]
Output: false
Example 3:
Input: root = []
Output: true
class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null) return true;
return maxDepth(root,1)!=-1;
}
public int maxDepth(TreeNode root, int dep){
if(root==null) return dep;
int left = maxDepth(root.left, dep);
int right = maxDepth(root.right, dep);
if(left==-1||right==-1||Math.abs(left-right)>1) return -1;
return Math.max(left,right)+1;
}
}