987. 二叉树的垂序遍历

二叉树的垂序遍历

解法一: 排序

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
32
33
34
35
36
37
38
39
40
41
42
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func verticalTraversal(root *TreeNode) [][]int {
var lists [][]int
var dfs func(*TreeNode, int, int)
dfs = func(node *TreeNode, col, row int) {
if node == nil {
return
}
lists = append(lists, []int{col, row, node.Val})
dfs(node.Left, col-1, row+1)
dfs(node.Right, col+1, row+1)
}
dfs(root, 0, 0)
sort.Slice(lists, func(i, j int) bool {
if lists[i][0] != lists[j][0] {
return lists[i][0] <= lists[j][0]
}
if lists[i][1] != lists[j][1] {
return lists[i][1] <= lists[j][1]
}
return lists[i][2] <= lists[j][2]
})
preCol := -1001
var ans [][]int
for _, list := range lists {
if preCol == list[0] {
last := len(ans) - 1
ans[last] = append(ans[last], list[2])
} else {
preCol = list[0]
ans = append(ans, []int{list[2]})
}
}
return ans
}
作者

wuhunyu

发布于

2024-02-13

更新于

2024-09-05

许可协议