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 c8f62df

Browse files
feat: add solutions to lc problem: No.0589 (doocs#2347)
No.0589.N-ary Tree Preorder Traversal
1 parent eade903 commit c8f62df

File tree

12 files changed

+600
-208
lines changed

12 files changed

+600
-208
lines changed

‎solution/0500-0599/0589.N-ary Tree Preorder Traversal/README.md‎

Lines changed: 208 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,11 @@
4545

4646
## 解法
4747

48-
### 方法一
48+
### 方法一:递归
49+
50+
我们可以递归地遍历整棵树。对于每个节点,先将节点的值加入答案,然后对该节点的每个子节点递归地调用函数。
51+
52+
时间复杂度 $O(n),ドル空间复杂度 $O(n)$。其中 $n$ 为节点数。
4953

5054
<!-- tabs:start -->
5155

@@ -60,16 +64,16 @@ class Node:
6064

6165

6266
class Solution:
63-
def preorder(self, root: 'Node') -> List[int]:
67+
def preorder(self, root: "Node") -> List[int]:
68+
def dfs(root):
69+
if root is None:
70+
return
71+
ans.append(root.val)
72+
for child in root.children:
73+
dfs(child)
74+
6475
ans = []
65-
if root is None:
66-
return ans
67-
stk = [root]
68-
while stk:
69-
node = stk.pop()
70-
ans.append(node.val)
71-
for child in node.children[::-1]:
72-
stk.append(child)
76+
dfs(root)
7377
return ans
7478
```
7579

@@ -94,22 +98,21 @@ class Node {
9498
*/
9599

96100
class Solution {
101+
private List<Integer> ans = new ArrayList<>();
102+
97103
public List<Integer> preorder(Node root) {
104+
dfs(root);
105+
return ans;
106+
}
107+
108+
private void dfs(Node root) {
98109
if (root == null) {
99-
returnCollections.emptyList();
110+
return;
100111
}
101-
List<Integer> ans = new ArrayList<>();
102-
Deque<Node> stk = new ArrayDeque<>();
103-
stk.push(root);
104-
while (!stk.isEmpty()) {
105-
Node node = stk.pop();
106-
ans.add(node.val);
107-
List<Node> children = node.children;
108-
for (int i = children.size() - 1; i >= 0; --i) {
109-
stk.push(children.get(i));
110-
}
112+
ans.add(root.val);
113+
for (Node child : root.children) {
114+
dfs(child);
111115
}
112-
return ans;
113116
}
114117
}
115118
```
@@ -138,17 +141,17 @@ public:
138141
class Solution {
139142
public:
140143
vector<int> preorder(Node* root) {
141-
if (!root) return {};
142144
vector<int> ans;
143-
stack<Node*> stk;
144-
stk.push(root);
145-
while (!stk.empty()) {
146-
Node* node = stk.top();
147-
ans.push_back(node->val);
148-
stk.pop();
149-
auto children = node->children;
150-
for (int i = children.size() - 1; i >= 0; --i) stk.push(children[i]);
151-
}
145+
function<void(Node*)> dfs = [&](Node* root) {
146+
if (!root) {
147+
return;
148+
}
149+
ans.push_back(root->val);
150+
for (auto& child : root->children) {
151+
dfs(child);
152+
}
153+
};
154+
dfs(root);
152155
return ans;
153156
}
154157
};
@@ -163,22 +166,19 @@ public:
163166
* }
164167
*/
165168
166-
func preorder(root *Node) []int {
167-
var ans []int
168-
if root == nil {
169-
return ans
170-
}
171-
stk := []*Node{root}
172-
for len(stk) > 0 {
173-
node := stk[len(stk)-1]
174-
ans = append(ans, node.Val)
175-
stk = stk[:len(stk)-1]
176-
children := node.Children
177-
for i := len(children) - 1; i >= 0; i-- {
178-
stk = append(stk, children[i])
169+
func preorder(root *Node) (ans []int) {
170+
var dfs func(*Node)
171+
dfs = func(root *Node) {
172+
if root == nil {
173+
return
174+
}
175+
ans = append(ans, root.Val)
176+
for _, child := range root.Children {
177+
dfs(child)
179178
}
180179
}
181-
return ans
180+
dfs(root)
181+
return
182182
}
183183
```
184184

@@ -196,20 +196,18 @@ func preorder(root *Node) []int {
196196
*/
197197

198198
function preorder(root: Node | null): number[] {
199-
const res = [];
200-
if (root == null) {
201-
return res;
202-
}
203-
const stack = [root];
204-
while (stack.length !== 0) {
205-
const { val, children } = stack.pop();
206-
res.push(val);
207-
const n = children.length;
208-
for (let i = n - 1; i >= 0; i--) {
209-
stack.push(children[i]);
199+
const ans: number[] = [];
200+
const dfs = (root: Node | null) => {
201+
if (!root) {
202+
return;
210203
}
211-
}
212-
return res;
204+
ans.push(root.val);
205+
for (const child of root.children) {
206+
dfs(child);
207+
}
208+
};
209+
dfs(root);
210+
return ans;
213211
}
214212
```
215213

@@ -247,10 +245,149 @@ int* preorder(struct Node* root, int* returnSize) {
247245
248246
<!-- tabs:end -->
249247
250-
### 方法二
248+
### 方法二:迭代(栈实现)
249+
250+
我们也可以用迭代的方法来解决这个问题。
251+
252+
我们使用一个栈来帮助我们得到前序遍历,我们首先把根节点入栈,因为前序遍历是根节点、左子树、右子树,栈的特点是先进后出,所以我们先把节点的值加入答案,然后对该节点的每个子节点按照从右到左的顺序依次入栈。循环直到栈为空。
253+
254+
时间复杂度 $O(n),ドル空间复杂度 $O(n)$。其中 $n$ 为节点数。
251255
252256
<!-- tabs:start -->
253257
258+
```python
259+
"""
260+
# Definition for a Node.
261+
class Node:
262+
def __init__(self, val=None, children=None):
263+
self.val = val
264+
self.children = children
265+
"""
266+
267+
268+
class Solution:
269+
def preorder(self, root: 'Node') -> List[int]:
270+
ans = []
271+
if root is None:
272+
return ans
273+
stk = [root]
274+
while stk:
275+
node = stk.pop()
276+
ans.append(node.val)
277+
for child in node.children[::-1]:
278+
stk.append(child)
279+
return ans
280+
```
281+
282+
```java
283+
/*
284+
// Definition for a Node.
285+
class Node {
286+
public int val;
287+
public List<Node> children;
288+
289+
public Node() {}
290+
291+
public Node(int _val) {
292+
val = _val;
293+
}
294+
295+
public Node(int _val, List<Node> _children) {
296+
val = _val;
297+
children = _children;
298+
}
299+
};
300+
*/
301+
302+
class Solution {
303+
public List<Integer> preorder(Node root) {
304+
if (root == null) {
305+
return Collections.emptyList();
306+
}
307+
List<Integer> ans = new ArrayList<>();
308+
Deque<Node> stk = new ArrayDeque<>();
309+
stk.push(root);
310+
while (!stk.isEmpty()) {
311+
Node node = stk.pop();
312+
ans.add(node.val);
313+
List<Node> children = node.children;
314+
for (int i = children.size() - 1; i >= 0; --i) {
315+
stk.push(children.get(i));
316+
}
317+
}
318+
return ans;
319+
}
320+
}
321+
```
322+
323+
```cpp
324+
/*
325+
// Definition for a Node.
326+
class Node {
327+
public:
328+
int val;
329+
vector<Node*> children;
330+
331+
Node() {}
332+
333+
Node(int _val) {
334+
val = _val;
335+
}
336+
337+
Node(int _val, vector<Node*> _children) {
338+
val = _val;
339+
children = _children;
340+
}
341+
};
342+
*/
343+
344+
class Solution {
345+
public:
346+
vector<int> preorder(Node* root) {
347+
if (!root) return {};
348+
vector<int> ans;
349+
stack<Node*> stk;
350+
stk.push(root);
351+
while (!stk.empty()) {
352+
Node* node = stk.top();
353+
ans.push_back(node->val);
354+
stk.pop();
355+
auto children = node->children;
356+
for (int i = children.size() - 1; i >= 0; --i) stk.push(children[i]);
357+
}
358+
return ans;
359+
}
360+
};
361+
```
362+
363+
```go
364+
/**
365+
* Definition for a Node.
366+
* type Node struct {
367+
* Val int
368+
* Children []*Node
369+
* }
370+
*/
371+
372+
func preorder(root *Node) []int {
373+
var ans []int
374+
if root == nil {
375+
return ans
376+
}
377+
stk := []*Node{root}
378+
for len(stk) > 0 {
379+
node := stk[len(stk)-1]
380+
ans = append(ans, node.Val)
381+
stk = stk[:len(stk)-1]
382+
children := node.Children
383+
for i := len(children) - 1; i >= 0; i-- {
384+
stk = append(stk, children[i])
385+
}
386+
}
387+
return ans
388+
}
389+
```
390+
254391
```ts
255392
/**
256393
* Definition for node.
@@ -265,17 +402,18 @@ int* preorder(struct Node* root, int* returnSize) {
265402
*/
266403

267404
function preorder(root: Node | null): number[] {
268-
const ans = [];
269-
const dfs = (root: Node | null) => {
270-
if (root == null) {
271-
return;
272-
}
273-
ans.push(root.val);
274-
for (const node of root.children) {
275-
dfs(node);
405+
const ans: number[] = [];
406+
if (!root) {
407+
return ans;
408+
}
409+
const stk: Node[] = [root];
410+
while (stk.length) {
411+
const { val, children } = stk.pop()!;
412+
ans.push(val);
413+
for (let i = children.length - 1; i >= 0; i--) {
414+
stk.push(children[i]);
276415
}
277-
};
278-
dfs(root);
416+
}
279417
return ans;
280418
}
281419
```

0 commit comments

Comments
(0)

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