判断二叉树是否平衡,就是将每个节点看作一个以此节点为root的子树,分别判断是否平衡~
是否平衡的标准是两个子树高度相减的绝对值<1~
高度的求法是两个子树的高度较大值+1~
这是一道简单的题,却没想到默写起来坑坑巴巴~ 真是伤心~
仔细想想还是自己递归没有掌握熟练~ 多多练习吧~
public boolean isBalance(Newtree root) {
if(root==null) {
return true;
}
if (Math.abs(high(root.lc)-high(root.rc))>1){
return false;
}
boolean l= isBalance(root.lc);
boolean r= isBalance(root.rc);
return l&&r;
}
public int high(Newtree root) {
if(root == null) {
return 0;
}
int hl = high(root.lc);
int hr = high(root.rc);
int h=hl>hr?hl+1:hr+1;
return h;
}
代码优化了一下:
class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null){
return true;
}
System.out.println(high(root.left)+" "+high(root.right));
if (Math.abs(high(root.left)-high(root.right))>1){
return false;
}
return isBalanced(root.left) && isBalanced(root.right);
}
public int high(TreeNode root){
if(root==null){
return 0;
}
return Math.max(high(root.left),high(root.right))+1;
}
}