Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 53801df

Browse files
Merge pull request SharingSource#153 from SharingSource/ac_oier
✨update: Modify 430
2 parents 5ef67ec + b620969 commit 53801df

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

‎LeetCode/421-430/430. 扁平化多级双向链表(中等).md‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,48 @@ class Solution {
8383
}
8484
}
8585
```
86+
* 时间复杂度:最坏情况下,每个节点会被访问 $h$ 次($h$ 为递归深度,最坏情况下 $h = n$)。整体复杂度为 $O(n^2)$
87+
* 空间复杂度:最坏情况下所有节点都分布在 `child` 中,此时递归深度为 $n$。复杂度为 $O(n)$
88+
89+
---
90+
91+
### 递归(优化)
92+
93+
在上述解法中,由于我们直接使用 `flatten` 作为递归函数,导致递归处理 $head.child$ 后不得不再进行遍历来找当前层的"尾结点",这导致算法复杂度为 $O(n^2)$。
94+
95+
一个可行的优化是,额外设计一个递归函数 `dfs` 用于返回扁平化后的链表"尾结点",从而确保我们找尾结点的动作不会在每层发生。
96+
97+
![image.png](https://pic.leetcode-cn.com/1632439410-oXoxbn-image.png)
98+
99+
代码:
100+
```Java
101+
class Solution {
102+
public Node flatten(Node head) {
103+
dfs(head);
104+
return head;
105+
}
106+
Node dfs(Node head) {
107+
Node last = head;
108+
while (head != null) {
109+
if (head.child == null) {
110+
last = head;
111+
head = head.next;
112+
} else {
113+
Node tmp = head.next;
114+
Node childLast = dfs(head.child);
115+
head.next = head.child;
116+
head.child.prev = head;
117+
head.child = null;
118+
if (childLast != null) childLast.next = tmp;
119+
if (tmp != null) tmp.prev = childLast;
120+
last = head;
121+
head = childLast;
122+
}
123+
}
124+
return last;
125+
}
126+
}
127+
```
86128
* 时间复杂度:$O(n)$
87129
* 空间复杂度:最坏情况下所有节点都分布在 `child` 中,此时递归深度为 $n$。复杂度为 $O(n)$
88130

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /