思路:
dfs,返回的是树的深度。
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root) return 0;
return dfs(root);
}
int dfs(TreeNode* root){
if(!root) return 0;
return max(dfs(root->left),dfs(root->right)) + 1;
}
};
评论区