Leetcode 110.平衡二叉树我可以问为什么我的解决方案有问题吗?

时间:2017-11-21 23:23:21

标签: java algorithm

原始问题附在此处:https://leetcode.com/problems/balanced-binary-tree/description/

public class BalancedBinaryTree {

    static boolean balance = true;

    public boolean isBalanced(TreeNode root) {
        if (root == null)
            return true;
        return (Math.abs(depth(root.left) - depth(root.right)) <= 1) && balance;
    }

    public int depth(TreeNode root) {
        if (balance) {
            if (root == null)
                return 0;

            int lengthOfLeft = depth(root.left);
            int lengthOfRight = depth(root.right);

            if (Math.abs(lengthOfLeft - lengthOfRight) > 1) {
                balance = false;
            }
            return Math.max(lengthOfLeft, lengthOfRight) + 1;
        } else {
            return 0;
        }
    }

1 个答案:

答案 0 :(得分:0)

试试这个。 基本上,你应该把平衡重新设置为真,因为从输出为正(预期为真)的测试到负数(期望为假)的测试将很重要。

 static boolean balance = true;

public boolean isBalanced(TreeNode root) {
    balance = true;
    if (root == null)
        return true;
    return (Math.abs(depth(root.left) - depth(root.right)) <= 1) && balance;
}

public int depth(TreeNode root) {
    if (balance) {
        if (root == null)
            return 0;

        int lengthOfLeft = depth(root.left);
        int lengthOfRight = depth(root.right);

        if (Math.abs(lengthOfLeft - lengthOfRight) > 1) {
            balance = false;
        }
        return Math.max(lengthOfLeft, lengthOfRight) + 1;
    } else {
        return 0;
    }
}