解析
设置全局变量保存最大深度,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;
}
};
本文介绍了一种使用深度优先遍历(DFS)算法来寻找二叉树最大深度的方法。通过设置全局变量保存最大深度,从根节点开始遍历,遇到叶子节点时检查并更新最大深度。代码实现简洁,易于理解。

被折叠的 条评论
为什么被折叠?



