带你快速刷完67道剑指offer
这是四则或许对你有帮助的讯息
1、👉 最近我发现了一个每日都会推送最新校招资讯的《校招日程》文档,其中包括往届补录、应届实习校招信息,比如各种大厂、国企、银行、事业编等信息都会定期更新,帮忙扩散一下。
2、😍 免费分享阿秀个人学习计算机以来的收集到的免费资源,点此白嫖。
3、🚀如果你想在校招中顺利拿到更好的offer,阿秀建议你多看看前人踩过的坑和留下的经验,事实上你现在遇到的大多数问题你的学长学姐师兄师姐基本都已经遇到过了。
4、🔥 欢迎准备计算机校招的小伙伴加入我的学习圈子,一个人踽踽独行真的不如一群人报团取暖,过去22届和23届的小伙伴好好跟着走下去的,最后基本都拿到了不错的offer!如果你需要《阿秀的学习笔记》网站中📚︎校招八股文相关知识点的PDF版本的话,可以点此下载 。
# No38、二叉树的深度
# 题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
# 示例1
输入
{1,2,3,4,5,#,6,#,#,7}
1
返回值
4
1
# 1、BFS,迭代版本
int TreeDepth(TreeNode* pRoot)
{
if (pRoot == nullptr) return 0;
queue<pair<TreeNode*, int>> q;
q.push(make_pair(pRoot, 1));
int maxDept = 1;
while (!q.empty()) {
TreeNode* curNode = q.front().first;
int curDepth = q.front().second;
q.pop();
if (curNode) {
maxDept = max(maxDept, curDepth);
q.push({ curNode->left,curDepth + 1 });
q.push({ curNode->right,curDepth + 1 });
}
}
return maxDept;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 2、递归法
int TreeDepth(TreeNode* pRoot)
{
if (pRoot == nullptr) return 0;
int leftDept = TreeDepth(pRoot->left) + 1, rightDept = TreeDepth(pRoot->right) + 1;
return max(leftDept, rightDept;
}
1
2
3
4
5
6
2
3
4
5
6
# 二刷:
# 1、很简单的递归方法
运行时间:2ms 占用内存:504k
int TreeDepth(TreeNode* pRoot)
{
if(pRoot == nullptr) return 0;
int leftDepth = TreeDepth(pRoot->left);
int rightDepth = TreeDepth(pRoot->right);
return 1 + max(leftDepth,rightDepth);
}
1
2
3
4
5
6
7
2
3
4
5
6
7