[leetcode] 110. 平衡二叉树

时间:2022-12-17 17:27:51

110. 平衡二叉树

实际上递归的求每一个左右子树的最大深度即可,如果差值大于1,返回一个-1的状态上去

class Solution {
    public boolean isBalanced(TreeNode root) {
        return depth(root)!=-1;
    }

    public int depth(TreeNode root) {
        if (null == root) return 0;
        int left = depth(root.left);
        int right = depth(root.right);

        if (left != -1 && right != -1 && Math.abs(left - right) <= 1) {
            return Math.max(left, right) + 1;
        } else {
            return -1;
        }
    }
}