题解 | #判断是不是平衡二叉树#
判断是不是平衡二叉树
http://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
思路: 计算每一个节点的树的高度 对每一个节点的左右子树高度进行判断,出现高度差大于1则返回
public boolean IsBalanced_Solution(TreeNode root) {
if (root==null){
return true;
}
int a=panduan(root.left);
int b=panduan(root.right);
int c=a-b;
if (c<-1||c>1){
return false;
}
boolean h=IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);
return h;
}
private static int panduan(TreeNode root) {
if (root==null){
return 0;
}
else {
return 1+Math.max(panduan(root.left),panduan(root.right));
}
}
}
查看20道真题和解析