Enter the root node of a binary tree and find the depth of the tree. The nodes (including root and leaf nodes) passing through from the root node to the leaf node in turn form a path of the tree, and the length of the longest path is the depth of the tree.
E.g:
Given a binary tree [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
Return its maximum depth 3.
prompt:
节点总数 <= 10000
I feel that the order of the question bank is not right, this question should be placed a little earlier
/**
* 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:
void dfs(TreeNode* root,int &ans,int shen)
{
if(root==NULL) return ;
ans=max(shen,ans);
dfs(root->left,ans,shen+1);
dfs(root->right,ans,shen+1);
}
int maxDepth(TreeNode* root) {
int ans=0;
dfs(root,ans,1);
return ans;
}
};