3. Given the following Go code snippet for top view, what will be printed?
type Node struct {
Val int
Left, Right *Node
}
func topView(root *Node) []int {
if root == nil {
return []int{}
}
type pair struct { node *Node; hd int }
queue := []pair{{root, 0}}
m := map[int]int{}
res := []int{}
for len(queue) > 0 {
p := queue[0]
queue = queue[1:]
if _, ok := m[p.hd]; !ok {
m[p.hd] = p.node.Val
}
if p.node.Left != nil {
queue = append(queue, pair{p.node.Left, p.hd - 1})
}
if p.node.Right != nil {
queue = append(queue, pair{p.node.Right, p.hd + 1})
}
}
keys := []int{}
for k := range m {
keys = append(keys, k)
}
sort.Ints(keys)
for _, k := range keys {
res = append(res, m[k])
}
return res
}
root := &Node{Val: 1}
root.Left = &Node{Val: 2}
root.Right = &Node{Val: 3}
root.Left.Right = &Node{Val: 4}
root.Left.Right.Right = &Node{Val: 5}
root.Left.Right.Right.Right = &Node{Val: 6}
fmt.Println(topView(root))