Skip to content

Commit 671dfdb

Browse files
author
CharonChui
committed
add notes
1 parent 7983655 commit 671dfdb

18 files changed

Lines changed: 343 additions & 2 deletions

‎Algorithm/74.填充每个节点的下一个右侧节点指针 II.md‎

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,10 @@ struct Node {
4545

4646
### 思路
4747

48+
49+
如果第N层的next已经连好了,我就能像遍历链表一样走完第N层,顺便把第N+1层也连好。
50+
51+
4852
#### 思路一: BFS层序遍历(最直观)
4953

5054
用队列做层序遍历,每层处理时把相邻节点连起来。
@@ -82,12 +86,47 @@ class Solution {
8286

8387
核心思路: 在当前层next已经建好,就可以像链表一样遍历当前层,同时为下一层简历next链接。
8488

89+
- curr: 当前层的遍历指针,像你在当前排走动
90+
- dummy: 哨兵,站在下一排的最坐标,作为起点,减少对起点的异常边界判断
91+
- tail: 下一排的最后一个,初始时就是dummy
8592

8693

94+
```kotlin
95+
class Solution {
96+
fun connect(root: Node?): Node? {
97+
var curr = root // 从根节点开始,逐层往下
98+
99+
while (curr != null) {
100+
// 每处理一层,都给下一层准备一个虚拟头节点
101+
val dummy = Node(0)
102+
var tail = dummy // tail 是下一层链表的末尾,初始指向 dummy
103+
104+
// 遍历当前层(因为上一轮已经连好了 next,所以可以直接用 next 遍历)
105+
while (curr != null) {
106+
if (curr.left != null) {
107+
tail.next = curr.left // 把左孩子接到下一层链表末尾
108+
tail = tail.next!! // tail 向后移
109+
}
110+
if (curr.right != null) {
111+
tail.next = curr.right // 把右孩子接到下一层链表末尾
112+
tail = tail.next!! // tail 向后移
113+
}
114+
curr = curr.next // 当前层向右走
115+
}
116+
117+
// 当前层处理完毕,下移到下一层的第一个节点
118+
curr = dummy.next
119+
}
120+
121+
return root
122+
}
123+
}
124+
```
125+
87126
### 复杂度
88127

89-
- 时间复杂度:
90-
- 空间复杂度:
128+
- 时间复杂度: O(n),每个节点只访问一次
129+
- 空间复杂度: 只用了dummy和tail两个额外的指针,没有队列
91130

92131

93132

File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
58.
2+
===
3+
4+
5+
### 题目
6+
7+
8+
9+
### 思路
10+
11+
12+
### 复杂度
13+
14+
- 时间复杂度:
15+
- 空间复杂度:
16+
17+
18+
19+
---
20+
21+
- [下一题]()
22+
23+
24+
---
25+
- 邮箱 :charon.chui@gmail.com
26+
- Good Luck!
27+
28+
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
58.
2+
===
3+
4+
5+
### 题目
6+
7+
8+
9+
### 思路
10+
11+
12+
### 复杂度
13+
14+
- 时间复杂度:
15+
- 空间复杂度:
16+
17+
18+
19+
---
20+
21+
- [下一题]()
22+
23+
24+
---
25+
- 邮箱 :charon.chui@gmail.com
26+
- Good Luck!
27+
28+
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
58.
2+
===
3+
4+
5+
### 题目
6+
7+
8+
9+
### 思路
10+
11+
12+
### 复杂度
13+
14+
- 时间复杂度:
15+
- 空间复杂度:
16+
17+
18+
19+
---
20+
21+
- [下一题]()
22+
23+
24+
---
25+
- 邮箱 :charon.chui@gmail.com
26+
- Good Luck!
27+
28+

0 commit comments

Comments
 (0)