110. Balanced Binary Tree
Determines if the given binary tree is height balanced.
For this problem, a height-balanced binary tree is defined as follows.
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
Limit:
The number of nodes in the tree is in the range [ 0, 5000].
-104 <= Node.val <= 104
Solution
class Solution {
boolean ans = true;
public int heightOfTree(TreeNode currentnode){
if(currentnode==null){
return 0;
}
int lh = heightOfTree(currentnode.left);
int rh = heightOfTree(currentnode.right);
int a = Math.abs(lh-rh);
if(a>1){
ans = false;
}
int height =Math.max(lh,rh)+1;
return height;
}
public boolean isBalanced(TreeNode root) {
heightOfTree(root);
return ans;
}
}
Comments
Post a Comment