题解 | #二叉树的最大深度#
二叉树的最大深度
https://www.nowcoder.com/practice/8a2b2bf6c19b4f23a9bdb9b233eefa73
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
static int _count =0;
class Solution {
public:
/**
*
* @param root TreeNode类
* @return int整型
*/
void dfs(TreeNode *tree,int temp)
{
// 如果结点达到终点,并且此时的temp值要更大的话,那么最大值更新
if(tree==nullptr && _count < temp)
{
_count = temp;
}
// dfs缩略版,这道题用bfs也是可以
if (tree!=nullptr) {
temp++;
dfs(tree->left,temp);
dfs(tree->right,temp);
}
}
int maxDepth(TreeNode* root) {
// write code here
int temp=0;
dfs(root,temp);
return _count;
}
};

