package main
import (
"fmt"
"sort"
)
type Node struct {
Val int
Left *Node
Right *Node
}
func TopView(root *Node) []int {
if root == nil {
return []int{}
}
type pair struct {
node *Node
hd int
}
queue := []pair{{root, 0}}
m := make(map[int]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 := make([]int, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Ints(keys)
res := make([]int, len(keys))
for i, k := range keys {
res[i] = m[k]
}
return res
}
func main() {
root := &Node{Val: 1}
root.Left = &Node{Val: 2}
root.Right = &Node{Val: 3}
root.Left.Left = &Node{Val: 4}
root.Left.Right = &Node{Val: 5}
root.Right.Left = &Node{Val: 6}
root.Right.Right = &Node{Val: 7}
topView := TopView(root)
fmt.Println(topView) // Output: [4 2 1 3 7]
}This code performs a breadth-first search on the binary tree, tracking horizontal distances to find the top view nodes.