1

LeetCode有问题。我使用一个简单的递归解决方案来解决它,但是运行时间很长,为 170 毫秒。然后我找到了一个类似的解决方案,它也是递归的,它的运行时间只有大约 10 毫秒。为什么?

我的解决方案:

class Solution
{
public:
    bool isBalanced(TreeNode* root)
    {
        if (root == nullptr)
            return true;

        bool left = isBalanced(root->left);
        bool right = isBalanced(root->right);

        bool curr = false;
        int sub = height(root->left) - height(root->right);
        if (sub < 2 && sub > -2)
            curr = true;

        return left && right && curr;
    }

private:
    int height(TreeNode* root)
    {
        if (root == nullptr)
            return 0;

        int leftHeight = height(root->left);
        int rightHeight = height(root->right);
        return (leftHeight > rightHeight) ? (leftHeight + 1) : (rightHeight + 1);
    }
};

我找到的快速解决方案:

class Solution {
public:
    bool isBalanced(TreeNode *root) {
        if (root==NULL) return true;

        int left = treeDepth(root->left); 
        int right = treeDepth(root->right);

        if (left-right>1 || left-right < -1) {
            return false;
        }
        return isBalanced(root->left) && isBalanced(root->right);
    }

    int treeDepth(TreeNode *root) {
        if (root==NULL){
            return 0;
        }

        int left=1, right=1;

        left += treeDepth(root->left);
        right += treeDepth(root->right);

        return left>right?left:right;
    }

};

谢谢!

4

1 回答 1

3

您的解决方案总是调用isBalancedand 。对于树中的每个节点。height

更快的解决方案需要treeDepth每个节点,但会提前退出并且isBalanced如果它知道树不平衡则不会调用。不调用不必要的(递归/昂贵)函数是一种优化。

于 2015-05-20T03:22:09.590 回答