牛客网 平衡二叉树

题目:

输入一棵二叉树,判断该二叉树是否是平衡二叉树。

解题:

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        return getDepth(root) != -1;//-1则不是平衡二叉树
    }
     
    private int getDepth(TreeNode root) {
        if (root == null) return 0;
        int left = getDepth(root.left);
        if (left == -1) return -1;
        int right = getDepth(root.right);
        if (right == -1) return -1;
        return Math.abs(left - right) > 1 ? -1 : 1 + Math.max(left, right);
    }
}

 

posted @ 2020-02-08 14:22  yanhowever  阅读(144)  评论(0编辑  收藏  举报