//Definition for binary tree
//struct TreeNode {
// int val;
// struct TreeNode *left;
// struct TreeNode *right;
// };
int maxDepth(struct TreeNode *root)
{
//
// Your code
//
}
Discuss中有如下答案:
if (root == NULL)
return 0;
return maxDepth(root->left)>maxDepth(root->right) ? maxDepth(root->left)+1 : maxDepth(root->right)+1;
该方法超时了,原因so明显,调用了too many maxDepth。
给出以下简洁的做法:
return root ? 1 + max(maxDepth(root->left), maxDepth(root->right)) : 0;
代码之美!