题解 | #平衡二叉树#

平衡二叉树

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

二叉树的深度是从根节点开始(其深度为1)自顶向下逐层累加的;而二叉树高度是从叶节点开始(其高度为1)自底向上逐层累加的。虽然树的深度和高度一样,但是具体到树的某个节点,其深度和高度是不一样的。

public class Solution {

    public boolean isBalance = true;

    public boolean IsBalanced_Solution(TreeNode root) {

        if (root == null) {
            return true;
        }

        treeDeep(root);
        return isBalance;
    }

    public int treeDeep (TreeNode root) {

        if (root == null || !isBalance) {
            return 0;
        }

        int left = treeDeep(root.left);

        int right= treeDeep(root.right);

        int heightMinus = Math.abs(left - right);

        if (heightMinus <= 1) {
            isBalance = true;
        } else {
            isBalance = false;
        }

        return Math.max(treeDeep(root.left), treeDeep(root.right)) + 1;
    }
}
全部评论

相关推荐

09-22 15:45
门头沟学院 Java
谁给娃offer我给...:我也遇到了,我说只要我通过面试我就去,实际上我根本就不会去😁
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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