Bird
Raised Fist0
DSA Goprogramming~20 mins

Top View of Binary Tree in DSA Go - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Top View Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Top View for a Simple Binary Tree
What is the output of the top view traversal for the given binary tree?
DSA Go
package main

import "fmt"

type Node struct {
    data  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}}
    hdMap := map[int]int{}
    minHd, maxHd := 0, 0
    result := []int{}

    for len(queue) > 0 {
        p := queue[0]
        queue = queue[1:]
        node, hd := p.node, p.hd

        if _, ok := hdMap[hd]; !ok {
            hdMap[hd] = node.data
            if hd < minHd {
                minHd = hd
            }
            if hd > maxHd {
                maxHd = hd
            }
        }

        if node.left != nil {
            queue = append(queue, pair{node.left, hd - 1})
        }
        if node.right != nil {
            queue = append(queue, pair{node.right, hd + 1})
        }
    }

    for i := minHd; i <= maxHd; i++ {
        result = append(result, hdMap[i])
    }
    return result
}

func main() {
    root := &Node{data: 1}
    root.left = &Node{data: 2}
    root.right = &Node{data: 3}
    root.left.right = &Node{data: 4}
    root.left.right.right = &Node{data: 5}
    root.left.right.right.right = &Node{data: 6}

    fmt.Println(topView(root))
}
A[2, 1, 3, 6]
B[1, 2, 3]
C[2, 1, 3, 4, 5, 6]
D[1, 2, 4, 5, 6]
Attempts:
2 left
💡 Hint
Think about horizontal distances and which nodes appear first at each horizontal distance.
🧠 Conceptual
intermediate
1:30remaining
Understanding Horizontal Distance in Top View
In the context of the top view of a binary tree, what does the 'horizontal distance' (hd) represent?
AThe vertical level of a node from the root
BThe distance of a node from the root measured horizontally, with root at 0, left child at hd-1, right child at hd+1
CThe depth of a node in the tree
DThe number of nodes between the root and the current node
Attempts:
2 left
💡 Hint
Horizontal distance helps to identify nodes aligned vertically when viewed from the top.
🔧 Debug
advanced
2:00remaining
Identify the Bug in Top View Implementation
What error will occur when running this code snippet for top view of a binary tree?
DSA Go
func topView(root *Node) []int {
    if root == nil {
        return []int{}
    }
    type pair struct {
        node *Node
        hd   int
    }
    queue := []pair{{root, 0}}
    hdMap := map[int]int{}
    minHd, maxHd := 0, 0
    result := []int{}

    for len(queue) > 0 {
        p := queue[0]
        queue = queue[1:]
        node, hd := p.node, p.hd

        hdMap[hd] = node.data
        if hd < minHd {
            minHd = hd
        }
        if hd > maxHd {
            maxHd = hd
        }

        if node.left != nil {
            queue = append(queue, pair{node.left, hd - 1})
        }
        if node.right != nil {
            queue = append(queue, pair{node.right, hd + 1})
        }
    }

    for i := minHd; i <= maxHd; i++ {
        result = append(result, hdMap[i])
    }
    return result
}
AInfinite loop because queue is never emptied
BSyntax error due to missing colon in map declaration
CThe map overwrites values, so the top view is incorrect
DRuntime panic due to nil pointer dereference
Attempts:
2 left
💡 Hint
Check how the map is updated for each horizontal distance.
🚀 Application
advanced
2:30remaining
Top View of a Complex Binary Tree
Given the binary tree below, what is the top view output? Tree structure: 10 / \ 20 30 / \ \ 40 60 50 / \ 70 80
A[40, 20, 60, 10, 30, 50, 80]
B[40, 20, 10, 30, 50]
C[20, 10, 30, 50, 80]
D[40, 20, 10, 30, 50, 80]
Attempts:
2 left
💡 Hint
Consider horizontal distances and which nodes appear first at each horizontal distance.
❓ Predict Output
expert
3:00remaining
Output of Top View with Multiple Nodes at Same Horizontal Distance
What is the output of the top view traversal for the following binary tree? Tree: 1 / \ 2 3 / \ \ 4 5 6 \ \ 7 8
DSA Go
package main

import "fmt"

type Node struct {
    data  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}}
    hdMap := map[int]int{}
    minHd, maxHd := 0, 0
    result := []int{}

    for len(queue) > 0 {
        p := queue[0]
        queue = queue[1:]
        node, hd := p.node, p.hd

        if _, ok := hdMap[hd]; !ok {
            hdMap[hd] = node.data
            if hd < minHd {
                minHd = hd
            }
            if hd > maxHd {
                maxHd = hd
            }
        }

        if node.left != nil {
            queue = append(queue, pair{node.left, hd - 1})
        }
        if node.right != nil {
            queue = append(queue, pair{node.right, hd + 1})
        }
    }

    for i := minHd; i <= maxHd; i++ {
        result = append(result, hdMap[i])
    }
    return result
}

func main() {
    root := &Node{data: 1}
    root.left = &Node{data: 2}
    root.right = &Node{data: 3}
    root.left.left = &Node{data: 4}
    root.left.right = &Node{data: 5}
    root.right.right = &Node{data: 6}
    root.left.right.right = &Node{data: 7}
    root.right.right.right = &Node{data: 8}

    fmt.Println(topView(root))
}
A[4, 2, 1, 3, 6, 8]
B[4, 2, 1, 5, 6, 8]
C[2, 1, 3, 6, 8]
D[4, 2, 1, 3, 7, 8]
Attempts:
2 left
💡 Hint
Remember only the first node at each horizontal distance is included in the top view.

Practice

(1/5)
1. What does the top view of a binary tree represent?
easy
A. All leaf nodes of the tree
B. Nodes visible when the tree is viewed from the left side
C. Nodes visible when the tree is viewed from above
D. Nodes visible when the tree is viewed from the right side

Solution

  1. Step 1: Understand the top view concept

    The top view of a binary tree includes all nodes visible when looking down vertically from above the tree.
  2. Step 2: Differentiate from other views

    Left or right views show nodes from side angles, while top view shows nodes from above.
  3. Final Answer:

    Nodes visible when the tree is viewed from above -> Option C
  4. Quick Check:

    Top view = nodes seen from above [OK]
Hint: Top view shows nodes visible from above only [OK]
Common Mistakes:
  • Confusing top view with left or right view
  • Including all leaf nodes as top view
  • Thinking top view shows all nodes
2. Which Go data structure is best suited to store nodes for computing the top view of a binary tree?
easy
A. Map with horizontal distance as key
B. Array
C. Slice
D. Linked list

Solution

  1. Step 1: Identify the need for horizontal distance mapping

    Top view requires tracking nodes by their horizontal distance from root to avoid duplicates.
  2. Step 2: Choose data structure supporting key-value pairs

    A map with horizontal distance as key stores the first node at each horizontal distance efficiently.
  3. Final Answer:

    Map with horizontal distance as key -> Option A
  4. Quick Check:

    Use map for horizontal distance keys [OK]
Hint: Use map keyed by horizontal distance for top view [OK]
Common Mistakes:
  • Using slice or array without horizontal distance keys
  • Using linked list which lacks key access
  • Ignoring horizontal distance concept
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))
medium
A. [2 1 3]
B. [2 1 3 6]
C. [2 1 4 5 6]
D. [1 2 3 4 5 6]

Solution

  1. Step 1: Traverse nodes with horizontal distances

    Root(1) at hd=0, Left(2) at hd=-1, Right(3) at hd=1, Left.Right(4) at hd=0 (ignored), Left.Right.Right(5) at hd=1 (ignored), Left.Right.Right.Right(6) at hd=2.
  2. Step 2: Collect first nodes at each horizontal distance

    hd=-1:2, hd=0:1, hd=1:3, hd=2:6
  3. Final Answer:

    [2 1 3 6] -> Option B
  4. Quick Check:

    Top view nodes by hd sorted: 2,1,3,6 [OK]
Hint: First node at each horizontal distance forms top view [OK]
Common Mistakes:
  • Including nodes overwritten at same horizontal distance
  • Ignoring horizontal distance ordering
  • Confusing top view with level order
4. The following Go code attempts to compute the top view of a binary tree but has a bug. What is the bug?
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:]
    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
}
medium
A. It overwrites nodes at the same horizontal distance, losing top view nodes
B. It does not handle nil root properly
C. It uses a slice instead of a queue
D. It does not sort the keys before output

Solution

  1. Step 1: Analyze map assignment inside loop

    The code assigns m[p.hd] = p.node.Val every time, overwriting previous values at same horizontal distance.
  2. Step 2: Understand top view requirement

    Top view requires storing only the first node encountered at each horizontal distance, so overwriting causes incorrect output.
  3. Final Answer:

    It overwrites nodes at the same horizontal distance, losing top view nodes -> Option A
  4. Quick Check:

    Overwrite causes wrong top view [OK]
Hint: Store first node per horizontal distance only [OK]
Common Mistakes:
  • Overwriting map entries instead of checking existence
  • Ignoring horizontal distance uniqueness
  • Not sorting keys before output
5. You have a binary tree where multiple nodes share the same horizontal distance and level. How should you modify the top view algorithm to always show the node with the smallest value at each horizontal distance?
hard
A. Store the last node encountered at each horizontal distance regardless of value
B. Use a stack instead of a queue for traversal
C. Ignore horizontal distance and print all nodes at the top level
D. Store the node with the smallest value for each horizontal distance, updating if a smaller value is found

Solution

  1. Step 1: Understand the problem with duplicates

    When nodes share horizontal distance and level, top view must pick one node per horizontal distance.
  2. Step 2: Modify map to track smallest value

    Instead of storing first node only, update stored node if a smaller value is found at the same horizontal distance.
  3. Step 3: Implement comparison logic

    Check if current node's value is smaller than stored; if yes, replace it in the map.
  4. Final Answer:

    Store the node with the smallest value for each horizontal distance, updating if a smaller value is found -> Option D
  5. Quick Check:

    Keep smallest value per horizontal distance [OK]
Hint: Update map only if new node value is smaller [OK]
Common Mistakes:
  • Ignoring node values when duplicates occur
  • Using last node instead of smallest value
  • Changing traversal order instead of map logic
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard