下面是执行超时的代码
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == nullptr)
return 0;
return maxDepth(root->left) > maxDepth(root->right) ? maxDepth(root->left) + 1 : maxDepth(root->right) + 1;
}
};
下面是改进后的代码
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == nullptr)
return 0;
int maxLeftDepth = maxDepth(root->left);
int maxRightDepth = maxDepth(root->right);
return maxLeftDepth > maxRightDepth ? maxLeftDepth + 1 : maxRightDepth + 1;
}
};
区别在于原来的写法做了4次递归运算
改进后的只做了2次