题解 | #平衡二叉树#

平衡二叉树

http://www.nowcoder.com/questionTerminal/8b3b95850edb4115918ecebdf1b4d222

几天没写代码,写个递归在这想了半个小时。
就递归地判断两个子树是否是平衡二叉树就玩了,递归出口条件死活想不出来。
打小就看准了我以后成不了气候

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root==null){
            return true;
        }
        if(Math.abs(getDepth(root.left,0)-getDepth(root.right,0))<=1){
            return IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);
        }
        return false;
    }
    public int getDepth(TreeNode root,int currentLength){
        if(root!=null){
            currentLength++;
            return Math.max(getDepth(root.left,currentLength),getDepth(root.right,currentLength));
        }
        return currentLength;
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-09 12:20
点赞 评论 收藏
分享
我看看你怎么个事来
牛牛爱吃草草:我看看你怎么个事来
点赞 评论 收藏
分享
Lorn的意义:你这标个前端是想找全栈吗?而且项目确实没什么含金量,技术栈太少了,边沉淀边找吧 现在学院本想就业好一点四年至少得高三模式两年加油吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务