题目如下
代码如下
就是平平无奇的dfs,注意递归的条件和出口就可以了
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
int ans=dfs(root);
return ans;
}
int dfs(TreeNode* root){
if(!root) return 0;
return max(dfs(root->left),dfs(root->right))+1;
}
};