为什么类似解决方案的运行时间如此不同?

时间:2015-05-20 03:14:16

标签: c++ recursion tree-balancing

LeetCode中有problem。我使用简单的递归解决方案来解决它,但运行时间很长,即170毫秒。然后我发现了一个类似的solution,它也是递归的,运行时间只有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;
    }

};

谢谢!

1 个答案:

答案 0 :(得分:3)

您的解决方案同时调用isBalancedheight始终。对于树中的每个节点。

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