## Sword refers to Offer 55-I. The depth of the binary tree

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;
}
};
``````

### Guess you like

Origin blog.csdn.net/qq_43624038/article/details/113775297
Recommended
Ranking
Daily