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 left and right subtrees of every node differ in height by no more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3 / \ 9 20 / \ 15 7 Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]:
1 / \ 2 2 / \ 3 3 / \ 4 4 Return false.
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
public bool IsBalanced(TreeNode root) {
if(root==null){
return true;
}
int left = Helper(root.left);
int right = Helper(root.right);
if(Math.Abs(left-right)>1){
return false;
}
return IsBalanced(root.left)&&IsBalanced(root.right);
}
private int Helper(TreeNode root){
if(root==null){
return 0;
}
int left = Helper(root.left);
int right = Helper(root.right);
return 1+Math.Max(left,right);
}
}
Time Complexity: O(n)
Space Complexity: O(1)


