Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
思路:先序
我的拙劣代码
class Solution {
public:
int maxDepth(TreeNode* root) {
int maxD = INT_MIN;
dfs(root, maxD, 0);
return maxD;
}
void dfs(TreeNode* root,int &maxD,int cnt){
if (!root){
maxD = maxD > cnt ? maxD : cnt;
return;
}
dfs(root->left, maxD, cnt + 1);
dfs(root->right, maxD, cnt + 1);
}
};
大神的代码
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root) return 0;
return max(maxDepth(root->left) + 1, maxDepth(root->right) + 1);
}
};