NC62 平衡二叉树
描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
平衡二叉树(Balanced Binary Tree),具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
注:我们约定空树是平衡二叉树。
示例1
输入:
{1,2,3,4,5,6,7}
复制
返回值:
true
public class Solution {
public int no_balance = -1 ;
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null){
return true ;
}
return maxDepth(root) != no_balance ;
}
public int maxDepth(TreeNode root){
if(root == null){
return 0 ;
}
int left = maxDepth(root.left) ;
int right = maxDepth(root.right) ;
if(left == no_balance || right == no_balance || Math.abs(left - right) > 1){
return no_balance ;
}
return Math.max(left , right) + 1;
}
}