写了几道递归题,果然写递归快了很多。
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root)
return 0;
int pl=1,pr=1;
if(!root->left&&!root->right)
return pl;
pl+=maxDepth(root->left);
pr+=maxDepth(root->right);
return pl>pr?pl:pr;
}
};
但看了标准还是不够简练,确实也没有必要定义pl和pr。如果可以用max函数确实挺好,不然要用三元运算也太长了
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root)
return 0;
return 1+max(maxDepth(root->left),maxDepth(root->right));
}
};