-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvertical-order-traversal-of-a-binary-tree.go
87 lines (68 loc) · 1.41 KB
/
vertical-order-traversal-of-a-binary-tree.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package verticalordertraversalofabinarytree
import (
"container/heap"
)
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
type Point struct {
Node *TreeNode
x int
y int
}
type PriorityQueue []*Point
func (pq PriorityQueue) Len() int {
return len(pq)
}
func (pq PriorityQueue) Less(i, j int) bool {
if pq[i].x != pq[j].x {
return pq[i].x < pq[j].x
}
if pq[i].y != pq[j].y {
return pq[i].y > pq[j].y
}
return pq[i].Node.Val < pq[i].Node.Val
}
func (pq PriorityQueue) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
}
func (pq *PriorityQueue) Push(x interface{}) {
item := x.(*Point)
*pq = append(*pq, item)
}
func (pq *PriorityQueue) Pop() interface{} {
n := len(*pq)
item := (*pq)[n-1]
(*pq)[n-1] = nil
*pq = (*pq)[:n-1]
return item
}
func verticalTraversal(root *TreeNode) [][]int {
res := [][]int{}
queue := make(PriorityQueue, 0)
traverse(root, 0, 0, &queue)
var prev *Point = nil
list := []int{}
for len(queue) > 0 {
p := heap.Pop(&queue).(*Point)
if prev == nil || p.x != prev.x {
if prev != nil {
res = append(res, list)
}
list = []int{}
}
list = append(list, p.Node.Val)
prev = p
}
res = append(res, list)
return res
}
func traverse(root *TreeNode, x int, y int, queue *PriorityQueue) {
if root != nil {
heap.Push(queue, &Point{Node: root, x: x, y: y})
traverse(root.Left, x-1, y-1, queue)
traverse(root.Right, x+1, y-1, queue)
}
}