给定一个二叉树,判断它是否是
平衡二叉树
示例 1:
输入:root = [3,9,20,null,null,15,7] 输出:true
示例 2:
输入:root = [1,2,2,3,3,null,null,4,4] 输出:false
示例 3:
输入:root = [] 输出:true
提示:
- 树中的节点数在范围
[0, 5000]
内 -104 <= Node.val <= 104
/**
* 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 !(ISs(root) == -1);
}
public int ISs(TreeNode root){
if(root == null) return 0;
int left = ISs(root.left);
if(left == -1) return -1;
int right = ISs(root.right);
if(right == -1) return -1;
return Math.Abs(left - right)>1?-1:(1+Math.Max(left,right));
}
}