Top View of Binary Tree


Top View of Binary Tree – GeeksforGeeks


Problem: Top View of Binary Tree

Problem Statement

Given a binary tree, return the top view of the tree.

The top view of a binary tree is the set of nodes visible when the tree is viewed from the top.
Return the nodes from leftmost to rightmost in the top view.


Examples

Example 1

Input:
        1
      /   \
     2     3
      \   / \
       4 5   6

Output: 2 1 3 6

Example 2

Input:
      10
     /  \
    20  30
          \
          40
            \
            60

Output: 20 10 30 60

Constraints


Intuition

We want to print only the first node visible at each horizontal distance (HD) from the root.


Approach (BFS with Horizontal Distance Mapping)

Steps

  1. Use a TreeMap<Integer, Integer> or HashMap + sorting to store first node at each HD.

  2. Use a Queue of Pair<Node, HD> to perform level-order traversal.

  3. For each node:

    • If HD is not in map, add it.

    • Enqueue left child with HD - 1 and right child with HD + 1.

  4. After traversal, extract values in ascending order of HDs.


Code (Java)

class Solution {
    static class Pair {
        Node node;
        int hd;
        Pair(Node node, int hd) {
            this.node = node;
            this.hd = hd;
        }
    }

    static ArrayList<Integer> topView(Node root) {
        ArrayList<Integer> result = new ArrayList<>();
        if (root == null) return result;

        Map<Integer, Integer> map = new TreeMap<>();
        Queue<Pair> q = new LinkedList<>();

        q.add(new Pair(root, 0));

        while (!q.isEmpty()) {
            Pair current = q.poll();
            Node node = current.node;
            int hd = current.hd;

            if (!map.containsKey(hd)) {
                map.put(hd, node.data);
            }

            if (node.left != null) {
                q.add(new Pair(node.left, hd - 1));
            }

            if (node.right != null) {
                q.add(new Pair(node.right, hd + 1));
            }
        }

        for (int val : map.values()) {
            result.add(val);
        }

        return result;
    }
}

Time and Space Complexity


Dry Run

Input:

        1
      /   \
     2     3
      \   / \
       4 5   6

HDs:

Map after traversal:
{-1: 2, 0: 1, +1: 3, +2: 6}

Output: [2, 1, 3, 6]


Conclusion