There is a problem in LeetCode. I use a straightforward recursive solution to solve it, but the run time is to long, which is 170ms. Then I found a similar solution, which also is recursive, and the run time of this is just about 10ms. Why?
My solution:
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);
}
};
The fast solution I found:
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;
}
};
Thank you!
Your solution calls both isBalanced
and height
, always. For every single node in the tree.
The faster solution calls treeDepth
for every single node, but bails out early and doesn't call isBalanced
if it knows the tree is not balanced. It's an optimization to not call unnecessary (recursive/expensive) functions.