589. N 叉树的前序遍历

N 叉树的前序遍历

解法一: 递归

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Definition for a Node.
* type Node struct {
* Val int
* Children []*Node
* }
*/

func preorder(root *Node) []int {
ans := []int{}
var dfs func(node *Node)
dfs = func(node *Node) {
if node == nil {
return
}
ans = append(ans, node.Val)
for _, child := range node.Children {
dfs(child)
}
}
dfs(root)
return ans
}

解法二: 迭代

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* Definition for a Node.
* type Node struct {
* Val int
* Children []*Node
* }
*/

func preorder(root *Node) []int {
ans := []int{}
if root == nil {
return ans
}
stack := []*Node{root}
for len(stack) > 0 {
node := stack[len(stack)-1]
stack = stack[:len(stack)-1]
ans = append(ans, node.Val)
for i := len(node.Children) - 1; i >= 0; i-- {
stack = append(stack, node.Children[i])
}
}
return ans
}
作者

wuhunyu

发布于

2024-02-18

更新于

2025-01-15

许可协议