题解 | #判断是不是平衡二叉树#

判断是不是平衡二叉树

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

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root == null){
            return true;
        }
        return isBalanced(root)[0] == 1;
    }
    //后序遍历
    public int[] isBalanced(TreeNode root){
        if(root == null){
            return new int[]{1,0};
        }
        int[] left = isBalanced(root.left);
        int[] right = isBalanced(root.right);
        if(left[0]==1 && right[0] == 1 && Math.abs(left[1]-right[1])<=1){
            return new int[]{1,Math.max(left[1],right[1])+1};
        }
        return new int[]{0,0};
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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