Skip to content

Commit d7ca98a

Browse files
committed
Create vertical-order-traversal-of-a-binary-tree.go
1 parent f6046ad commit d7ca98a

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
//https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/
2+
3+
package vertical_order_traversal_of_a_binary_tree
4+
5+
import "sort"
6+
7+
type TreeNode struct {
8+
Val int
9+
Left *TreeNode
10+
Right *TreeNode
11+
}
12+
13+
type Data struct {
14+
Val int
15+
Depth int
16+
}
17+
18+
func verticalTraversal(root *TreeNode) [][]int {
19+
m := make(map[int]map[int][]Data)
20+
traverse(root, 0, 0, m)
21+
result := make([][]int, 0)
22+
for i := -1000; i <= 1000; i++ {
23+
if _, ok := m[i]; !ok {
24+
continue
25+
}
26+
tmp := make([]Data, 0)
27+
for j := 0; j <= 1000; j++ {
28+
if _, ok := m[i][j]; !ok {
29+
continue
30+
}
31+
tmp = append(tmp, m[i][j]...)
32+
}
33+
sort.Slice(tmp, func(i, j int) bool {
34+
if tmp[i].Depth == tmp[j].Depth {
35+
return tmp[i].Val < tmp[j].Val
36+
}
37+
return tmp[i].Depth < tmp[j].Depth
38+
})
39+
tmp2 := make([]int, 0)
40+
for _, v := range tmp {
41+
tmp2 = append(tmp2, v.Val)
42+
}
43+
result = append(result, tmp2)
44+
}
45+
return result
46+
}
47+
48+
func traverse(root *TreeNode, x, y int, m map[int]map[int][]Data) {
49+
if root == nil {
50+
return
51+
}
52+
if _, ok := m[x]; !ok {
53+
m[x] = make(map[int][]Data)
54+
}
55+
if _, ok := m[x][y]; !ok {
56+
m[x][y] = make([]Data, 0)
57+
}
58+
m[x][y] = append(m[x][y], Data{Val: root.Val, Depth: y})
59+
traverse(root.Left, x-1, y+1, m)
60+
traverse(root.Right, x+1, y+1, m)
61+
}

0 commit comments

Comments
 (0)