forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.go
45 lines (44 loc) · 802 Bytes
/
Solution2.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
43
44
45
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func verticalOrder(root *TreeNode) [][]int {
ans := [][]int{}
if root == nil {
return ans
}
d := map[int][]int{}
q := []pair{pair{root, 0}}
for len(q) > 0 {
for n := len(q); n > 0; n-- {
p := q[0]
q = q[1:]
root = p.node
offset := p.offset
d[offset] = append(d[offset], root.Val)
if root.Left != nil {
q = append(q, pair{root.Left, offset - 1})
}
if root.Right != nil {
q = append(q, pair{root.Right, offset + 1})
}
}
}
idx := []int{}
for i := range d {
idx = append(idx, i)
}
sort.Ints(idx)
for _, i := range idx {
ans = append(ans, d[i])
}
return ans
}
type pair struct {
node *TreeNode
offset int
}