Skip to content

Commit 5d511de

Browse files
authored
Merge pull request gzc426#383 from Longerhaha/master
更新104题解至乔戈里leetcode每日一题
2 parents 9a8168d + 1a4dbd0 commit 5d511de

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
## 104_Maximum Depth of Binary Tree(二叉树的最大深度)
2+
## 1 问题描述、输入输出与样例
3+
### 1.1 问题描述
4+
给定一个二叉树,找出其最大深度。<br>
5+
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。<br>
6+
__说明__: 叶子节点是指没有子节点的节点。
7+
### 1.2 输入与输出
8+
输入:
9+
* TreeNode* root:二叉树的根节点
10+
11+
输出:
12+
* int:最远叶子节点的最长路径上的节点数
13+
### 1.3 样例
14+
#### 1.3.1 样例1
15+
输入: 给定二叉树:[3,9,20,null,null,15,7]
16+
17+
3
18+
/ \
19+
9 20
20+
/ \
21+
15 7
22+
23+
输出: 3
24+
25+
## 2 思路描述与代码
26+
### 2.1 思路描述(基于队列的层次遍历方法)
27+
利用队列做层次遍历,遍历的时候用 depth 记录当前层遍历的深度,遍历结束后返回其深度。
28+
```cpp
29+
初始化深度 depth 为0;
30+
将二叉树根节点压入队列;
31+
while( 队列不空 ){
32+
深度 depth 加1
33+
获取当前层的深度 layer_len
34+
35+
for( int i = 0; i < layer_len; i++ ){
36+
弹出一个节点;
37+
如果该节点有孩子节点,则入队;
38+
}
39+
}
40+
返回 depth;
41+
```
42+
### 2.2 代码
43+
```cpp
44+
int maxDepth(TreeNode* root) {
45+
queue<TreeNode*> q;
46+
//初始化深度为0
47+
int depth = 0;
48+
//将头结点压入队列
49+
if(root)
50+
q.push(root);
51+
//利用队列做二叉树的层次遍历
52+
while( !q.empty() ){
53+
//深度加1
54+
depth += 1;
55+
//获取当前层的深度
56+
int layer_len = q.size();
57+
//层次遍历的所有节点
58+
//如果该节点有孩子节点,则入队
59+
for( int i = 0; i < layer_len; i++ ){
60+
TreeNode* tmp = q.front();
61+
q.pop();
62+
if(tmp->left)
63+
q.push(tmp->left);
64+
65+
if(tmp->right)
66+
q.push(tmp->right);
67+
}
68+
}
69+
return depth;
70+
}
71+
```
72+
## 3 思考与拓展
73+
### 3.1 思考
74+
有了101、102、103题的练手,本题就是易如反掌。本方法可以看做BFS,那当然还有一种DFS的做法了。
75+
#### 3.1.1 其他方法
76+
#### 3.1.1.1 递归法
77+
根节点的深度就是其左子树和右子树的深度的最大值加1。
78+
```cpp
79+
int maxDepth(TreeNode* root) {
80+
if(root == nullptr) return 0;
81+
else return max(maxDepth(root->left), maxDepth(root->right)) + 1;
82+
}
83+
```
84+
#### 3.1.2 复杂度分析
85+
方法|空间复杂度|时间复杂度
86+
--- | --- | ---
87+
基于队列的层次遍历方法|O(2^h),h是树的高度|O(n)
88+
递归法|O(n)|O(n)
89+
#### 3.1.3 难点分析
90+
1. 使用递归方法时要得到递归的公式
91+
2. 使用队列方法时需要注意深度加1的条件必须是当前层所有节点遍历结束。
92+
### 3.2 拓展
93+
如果让你求最远叶子节点的最长路径呢?

0 commit comments

Comments
 (0)