如果你想在校招中顺利拿到更好的offer,阿秀建议你多看看前人的经验 ,比如准备 、简历 、实习 、校招总结 、offer选择 、也欢迎来一起参加秋招打卡活动 等;如果你是计算机小白,学习/转行/校招路上感到迷茫或者需要帮助,可以点此联系阿秀;免费分享阿秀个人学习计算机以来的收集到的好资源,点此白嫖;如果你需要《阿秀的学习笔记》网站中求职相关知识点的PDF版本的话,可以点此下载
# 104. 二叉树的最大深度
力扣原题链接(点我直达) (opens new window)
难度简单480收藏分享切换为英文关注反馈
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
1
2
3
4
5
2
3
4
5
返回它的最大深度 3 。
# 1、自己写的,速度,时间都不太好啊
执行用时 :20 ms, 在所有 C++ 提交中击败了19.82%的用户
内存消耗 :20.5 MB, 在所有 C++ 提交中击败了5.06%的用户
class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root ) return 0;
if (root->left && root->right) return 1+max(maxDepth(root->right),maxDepth(root->left));
if (!root->left) return 1+ maxDepth(root->right);
else return 1+maxDepth(root->left);
}
};
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 2、另一种变种
执行用时 :12 ms, 在所有 C++ 提交中击败了73.48%的用户
内存消耗 :20.7 MB, 在所有 C++ 提交中击败了5.14%的用户
int maxDepth(TreeNode* root) {
if (!root ) return 0;
int left_depth = maxDepth(root->left) + 1, right_depth = maxDepth(root->right) +1;
return max(left_depth,right_depth);
}
1
2
3
4
5
2
3
4
5
# 3、BFS可以防止爆栈
执行用时 :12 ms, 在所有 C++ 提交中击败了73.48%的用户
内存消耗 :20.8 MB, 在所有 C++ 提交中击败了5.14%的用户
int maxDepth(TreeNode* root) {
if (!root) return 0;
int max_dept = 0;
queue<pair<TreeNode*, int> > q;
q.push({ root,1 });
while (!q.empty()) {
TreeNode* curr_node = q.front().first;
int curr_dept = q.front().second;
q.pop();
if (curr_node) {
max_dept = max(max_dept, curr_dept);
q.push({ curr_node->left,curr_dept + 1 });
q.push({ curr_node->right,curr_dept + 1 });
}
}
return max_dept;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17