Given a binary tree, determine if it is height-balanced.
/**
* 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)
{
return Balanced(root) >= 0;
}
public int Balanced(TreeNode root)
{
if (root == null)
return 0;
var lh = Balanced(root.left);
if (lh == -1)
return -1;
var rh = Balanced(root.right);
if (rh == -1)
return -1;
if ((lh > rh + 1) || (rh > lh + 1))
return -1;
else
return Math.Max(lh, rh)+1;
}
}