解析
设置全局变量保存最大深度,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 max_depth = -1;
void dfs(TreeNode *t, int cnt){
if(!t->left && !t->right){
max_depth = cnt > max_depth ? cnt : max_depth;
return;
}
if(t->left) dfs(t->left, cnt + 1);
if(t->right) dfs(t->right, cnt + 1);
}
int maxDepth(TreeNode* root) {
if(!root) return 0;
dfs(root, 1);
return max_depth;
}
};