590. 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 postorder(root *Node) []int {
ans := []int{}
var dfs func(node *Node)
dfs = func(node *Node) {
if node == nil {
return
}
for _, child := range node.Children {
dfs(child)
}
ans = append(ans, node.Val)
}
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
25
26
27
28
29
30
31
/**
* Definition for a Node.
* type Node struct {
* Val int
* Children []*Node
* }
*/

func postorder(root *Node) []int {
ans := []int{}
if root == nil {
return ans
}
stack := []*Node{root}
set := make(map[*Node]bool)
for len(stack) > 0 {
node := stack[len(stack)-1]
stack = stack[:len(stack)-1]
n := len(node.Children)
if n > 0 && !set[node] {
stack = append(stack, node)
set[node] = true
for i := n - 1; i >= 0; i-- {
stack = append(stack, node.Children[i])
}
} else {
ans = append(ans, node.Val)
}
}
return ans
}
作者

wuhunyu

发布于

2024-02-19

更新于

2025-01-15

许可协议