Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»Data Structures & Algorithms»Top View of Binary Tree | BFS with Horizontal Distance Mapping
    Data Structures & Algorithms

    Top View of Binary Tree | BFS with Horizontal Distance Mapping

    Anirudh KhuranaBy Anirudh Khurana2 September 2025Updated:16 November 2026No Comments6 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Featured image of a question to solve Top View of Binary Tree
    Share
    Facebook Twitter LinkedIn Pinterest Email

    The Top View of Binary Tree problem asks us to return the set of nodes visible when looking at the binary tree from above.

    • Each node has a horizontal distance (HD) from the root:
      • Root → HD = 0
      • Left child → HD - 1
      • Right child → HD + 1
    • For each HD, the first node encountered during level-order traversal (BFS) is part of the top view.

    We must output the nodes from leftmost HD to rightmost HD.

    Here’s the [Problem Link] to begin with.


    Example

    Example 1

    Input: 
          1
         / \
        2   3
         \
          4
           \
            5
             \
              6
    
    Output: [2, 1, 3, 6]
    Explanation: From the top, nodes 2, 1, 3, and 6 are visible.

    Example 2

    Input:
           10
          /  \
         20   30
        /  \
       40  60
    
    Output: [40, 20, 10, 30]

    Interactive Visualizer: BFS with Horizontal Distance

    Pick an example or type a tree in level order (use null for missing children), then press Next. Each visited node shows its horizontal distance (hd); green nodes are the ones visible from the top.



    Intuition and Approach

    The key idea is to track the horizontal distance (HD) of each node during traversal.

    1. Start with the root at HD = 0.
    2. Use BFS (level-order traversal) to ensure that the first node at each HD is captured.
    3. Maintain a dictionary hd_map where:
      • Key = HD
      • Value = Node data
      • Only store the first occurrence of each HD.
    4. Traverse the entire tree, updating left and right children with HD – 1 and HD + 1.
    5. Sort keys of hd_map and return values in order.

    This guarantees that we collect the correct top view.


    Code Implementation

    # Tree Node
    # class Node:
    #     def __init__(self, val):
    #         self.right = None
    #         self.data = val
    #         self.left = None
    
    from collections import deque
    
    class Solution:
        def topView(self, root):
            if not root:
                return []
            
            # dictionary to store first node for each horizontal distance
            hd_map = {}
            
            # queue for BFS -> stores (node, horizontal_distance)
            q = deque([(root, 0)])
            
            while q:
                node, hd = q.popleft()
                
                # store the first node we encounter at this HD
                if hd not in hd_map:
                    hd_map[hd] = node.data
                
                # add left and right children with updated HD
                if node.left:
                    q.append((node.left, hd - 1))
                if node.right:
                    q.append((node.right, hd + 1))
            
            # extract results sorted by horizontal distance
            result = [hd_map[key] for key in sorted(hd_map.keys())]
            return result
    /* Tree Node
    class Node {
        int data;
        Node left, right;
        Node(int val) { data = val; left = right = null; }
    } */
    
    class Solution {
        static ArrayList<Integer> topView(Node root) {
            ArrayList<Integer> result = new ArrayList<>();
            if (root == null) return result;
    
            // map to store first node for each horizontal distance (TreeMap keeps HDs sorted)
            Map<Integer, Integer> hdMap = new TreeMap<>();
    
            // queue for BFS -> stores (node, horizontal_distance)
            Queue<Node> q = new LinkedList<>();
            Queue<Integer> hds = new LinkedList<>();
            q.add(root);
            hds.add(0);
    
            while (!q.isEmpty()) {
                Node node = q.poll();
                int hd = hds.poll();
    
                // store the first node we encounter at this HD
                hdMap.putIfAbsent(hd, node.data);
    
                // add left and right children with updated HD
                if (node.left != null) { q.add(node.left); hds.add(hd - 1); }
                if (node.right != null) { q.add(node.right); hds.add(hd + 1); }
            }
    
            // extract results sorted by horizontal distance
            result.addAll(hdMap.values());
            return result;
        }
    }
    /* Tree Node
    struct Node {
        int data;
        Node* left;
        Node* right;
    }; */
    
    class Solution {
    public:
        vector<int> topView(Node* root) {
            if (!root) return {};
    
            // map to store first node for each horizontal distance (std::map keeps HDs sorted)
            map<int, int> hdMap;
    
            // queue for BFS -> stores (node, horizontal_distance)
            queue<pair<Node*, int>> q;
            q.push({root, 0});
    
            while (!q.empty()) {
                auto [node, hd] = q.front();
                q.pop();
    
                // store the first node we encounter at this HD
                if (hdMap.find(hd) == hdMap.end()) {
                    hdMap[hd] = node->data;
                }
    
                // add left and right children with updated HD
                if (node->left) q.push({node->left, hd - 1});
                if (node->right) q.push({node->right, hd + 1});
            }
    
            // extract results sorted by horizontal distance
            vector<int> result;
            for (auto& [hd, val] : hdMap) result.push_back(val);
            return result;
        }
    };

    Code Explanation

    • BFS Traversal:
      • Uses a queue to traverse the tree level by level.
    • Horizontal Distance (HD):
      • Root = 0, left child = -1, right child = +1.
    • hd_map:
      • Captures only the first node at each HD.
      • Ensures top-most node is chosen.
    • Sorting:
      • Keys are sorted to print nodes from leftmost to rightmost.

    Dry Run

    Input Tree:

          1
         / \
        2   3
         \
          4
           \
            5
             \
              6

    Step-by-step BFS traversal:

    1. Start → (1, 0) → store hd_map[0] = 1.
    2. Left → (2, -1) → store hd_map[-1] = 2.
    3. Right → (3, +1) → store hd_map[1] = 3.
    4. Next → (4, 0) → already exists, ignore.
    5. Next → (5, 1) → already exists, ignore.
    6. Next → (6, 2) → store hd_map[2] = 6.

    Final hd_map = {-1:2, 0:1, 1:3, 2:6}

    Sorted output = [2, 1, 3, 6]


    Time and Space Complexity

    • Time Complexity:
      • BFS traversal → O(N)
      • Sorting keys of hd_map → O(K log K), where K = number of unique HDs
      • Total → O(N log K)
    • Space Complexity:
      • Dictionary for storing nodes → O(K)
      • Queue for BFS → O(N)
      • Total → O(N)

    Conclusion

    The Top View of Binary Tree problem is solved efficiently using BFS and horizontal distance mapping.

    • Each node is assigned an HD.
    • The first node encountered at each HD is chosen.
    • Sorting ensures correct left-to-right order.

    This method runs in O(N log K) time and O(N) space, making it optimal for large binary trees.


    Frequently Asked Questions

    What is the top view of a binary tree?

    It is the set of nodes you would see looking at the tree from above, listed from left to right. For each horizontal position only the highest node is visible.

    What is horizontal distance in a binary tree?

    The root has horizontal distance (HD) 0. Moving to a left child subtracts 1 and moving to a right child adds 1. Nodes with the same HD sit in the same vertical column.

    Why is BFS used instead of DFS for the top view?

    BFS visits nodes level by level, so the first node it reaches at each HD is always the highest one. A plain DFS can reach a deeper node first, so it would need extra depth tracking to get the right answer.

    What is the time complexity of the top view solution?

    BFS visits every node once, which is O(n). Sorting the HD keys adds O(w log w), where w is the width of the tree. You can make it O(n) by tracking the minimum and maximum HD instead of sorting.

    What is the difference between the top view and the bottom view?

    The top view keeps the first node seen at each HD during BFS. The bottom view keeps the last one, so you simply overwrite the map entry every time instead of skipping it.


    Join our Advance DSA COURSE

    For any changes to the article, kindly email at co**@**********ug.in or contact us at +91-9712928220.

    Binary Trees Medium
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleVertical Order Traversal of a Binary Tree | Leetcode 987 | BFS + Sorting Solution
    Next Article Bottom View of Binary Tree | BFS with Horizontal Distance Mapping
    Anirudh Khurana
    • Website

    Anirudh Khurana is the founder of Code and Debug, an Indian EdTech platform that helps students and working professionals crack coding interviews and move into data and AI roles. He teaches DSA, Python, SQL, data engineering and machine learning through live bootcamps and his YouTube channel, Code and Debug, which has over 50,000 subscribers. Every guide on this blog is written or reviewed by him and tested with real code.

    Related Posts

    Data Structures & Algorithms

    DSA Interview Cheat Sheet: All Patterns You Need to Know

    4 April 2026
    Data Structures & Algorithms

    Symmetric Tree | Leetcode 101 | Recursive DFS Approach

    2 September 2025
    Data Structures & Algorithms

    Binary Tree Right Side View | Leetcode 199 | BFS and DFS Approaches

    2 September 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • AI & Machine Learning (8)
    • Data Structures & Algorithms (241)
      • Beginner (82)
      • Expert (52)
      • Intermediate (106)
    • Interview Questions (6)
    • Pandas (1)
    • Python (1)
    • Resume (1)
    • SQL (2)
    Recent Posts

    Normalization in DBMS: 1NF, 2NF and 3NF With SQL Examples

    25 November 2026

    100 Machine Learning Interview Questions and Answers (Freshers to Experienced)

    25 November 2026

    K-Means Clustering in Machine Learning: An Interactive Guide (with Python)

    20 November 2026

    Decision Tree in Machine Learning: An Interactive Guide (with Python)

    18 November 2026

    Support Vector Machine (SVM) in Machine Learning: An Interactive Guide

    16 November 2026
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.