104. 二叉树的最大深度
作者:互联网
✅做题思路or感想:
- 直接递归到叶子节点,然后更新最大值就好了
class Solution {
public:
int result = 1;
void dfs(TreeNode* cur, int sum) {
if (cur->left == nullptr && cur->right == nullptr) { //递归到叶子节点时,就更新最大值
result = max(result, sum);
}
if (cur->left)dfs(cur->left, sum + 1);
if (cur->right)dfs(cur->right, sum + 1);
}
int maxDepth(TreeNode* root) {
if (root == nullptr)return 0; //防止奇怪用例
dfs(root, 1);
return result;
}
};
标签:right,cur,int,sum,dfs,result,深度,104,二叉树 来源: https://www.cnblogs.com/doomaa/p/16062058.html