题解 | #平衡二叉树#
平衡二叉树
http://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
递归标准思路,拆解子问题
public class Solution {
static boolean res=true;
public boolean IsBalanced_Solution(TreeNode root) {
if(root==null){
return true;
}
fun(root);
return res;
}
//返回当前树深度度
public int fun(TreeNode root){
if(root==null){
return 0;
}
int leftlength=fun(root.left);
int rightlength=fun(root.right);
//如果当前节点的左右子树深度差超过1,直接把结果标识更新为false
if(Math.abs(leftlength-rightlength)>1){
res=false;
}
//左右子树深度合法,则返回大深度+1(加上当前头)
return Math.max(leftlength,rightlength)+1;
}
}
查看8道真题和解析