题解 | #平衡二叉树#

平衡二叉树

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

查看每个树的深度,相差2返回false,相差小于等于1,没有差2的返回true

import java.util.*;
public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root == null){
            return true;
        }
        Queue<TreeNode> we = new LinkedList<TreeNode>();
        we.offer(root);
        TreeNode p1;
        TreeNode p2;
        int n,p;
        while(!we.isEmpty()){
            p1 = we.poll();
            n = deep(p1.left);
            p = deep(p1.right);
            if(n-p==2 || p-n==2){
                return false;
            }
            if(p1.left != null){
                we.offer(p1.left);
            }
            if(p1.right != null){
                we.offer(p1.right);
            }
            
        }
        return true;
    }
    public int deep(TreeNode root){
        if(root == null){
            return 0;
        }
        return (deep(root.left)+1) > (deep(root.right)+1) ? (deep(root.left)+1) : (deep(root.right)+1);
    }
}
全部评论

相关推荐

烤点老白薯:他第二句话的潜台词是想让你帮他点个瑞幸或者喜茶啥的
mt对你说过最有启发的一...
点赞 评论 收藏
分享
jay118_:实在担心的话,就把你账号里面的认证人脸改成你室友的脸,让他每天帮你刷。要是人脸写死了就每天打视频电话刷脸。办法总比困难多。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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