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;
}
};
谢谢!