The Wayback Machine - https://web.archive.org/web/20241202151723/https://www.geeksforgeeks.org/print-nodes-top-view-binary-tree/
Open In App

Print Nodes in Top View of Binary Tree

Last Updated : 28 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a binary tree. The task is to find the top view of the binary tree. The top view of a binary tree is the set of nodes visible when the tree is viewed from the top.

Note: 

  • Return the nodes from the leftmost node to the rightmost node.
  • If two nodes are at the same position (horizontal distance) and are outside the shadow of the tree, consider the leftmost node only. 

Examples:

Example 1 : The Green colored nodes represents the top view in the below Binary tree.

Print-Nodes-in-Top-View-of-Binary-Tree-2


Example 2: The Green colored nodes represents the top view in the below Binary tree.

Print-Nodes-in-Top-View-of-Binary-Tree-4

Using DFS – O(n * log n) Time and O(n) Space

The idea is to use a Depth-First Search (DFS) approach to find the top view of a binary tree. Start from the root node with a horizontal distance of 0. As we traverse the tree, store each node’s value if it’s the first node encountered at its horizontal distance or if it’s at a higher level.

C++
// C++ program to print top
// view of binary tree

#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* left;
    Node* right;

    Node(int val) {
        data = val;
        left = right = nullptr;
    }
};

// DFS Helper to store top view nodes
void dfs(Node* node, int hd, int level, map<int, pair<int, int>>& topNodes) {
    if (!node) return;

    // If horizontal distance is encountered for 
    // the first time or if it's at a higher level
    if (topNodes.find(hd) == topNodes.end() || 
        topNodes[hd].second > level) {
        topNodes[hd] = {node->data, level};
    }

    // Recur for left and right subtrees
    dfs(node->left, hd - 1, level + 1, topNodes);
    dfs(node->right, hd + 1, level + 1, topNodes);
}

// DFS Approach to find the top view of a binary tree
vector<int> topView(Node* root) {
    vector<int> result;
    if (!root) return result;
    
    // Horizontal distance -> {node's value, level}
    map<int, pair<int, int>> topNodes; 
    
    // Start DFS traversal
    dfs(root, 0, 0, topNodes);

    // Collect nodes from the map
    for (auto it : topNodes) {
        result.push_back(it.second.first);
    }

    return result;
}


int main() {
    
    // Create a sample binary tree
    //     1
    //    / \
    //   2   3
    //  / \ / \
    // 4  5 6  7

    Node* root = new Node(1);
    root->left = new Node(2);       
    root->right = new Node(3);            
    root->left->left = new Node(4);     
    root->left->right = new Node(5);   
    root->right->left = new Node(6);   
    root->right->right = new Node(7); 

    vector<int> result = topView(root);
    for (int i : result) {
        cout << i << " ";
    }
    return 0;
}
Java
// Java program to print top view of binary tree

import java.util.*;

class Node {
    int data;
    Node left, right;

    public Node(int val) {
        data = val;
        left = right = null;
    }
}

class Pair<U, V> {
    public U first;
    public V second;

    public Pair(U first, V second) {
        this.first = first;
        this.second = second;
    }

    public U getKey() {
        return first;
    }

    public V getValue() {
        return second;
    }
}

class GfG {

    // DFS Helper to store top view nodes
    static void dfs(Node node, int hd, int level, Map<Integer, Pair<Integer, Integer>> topNodes) {
        if (node == null) return;

        // If horizontal distance is encountered for 
        // the first time or if it's at a higher level
        if (!topNodes.containsKey(hd) || topNodes.get(hd).getValue() > level) {
            topNodes.put(hd, new Pair<>(node.data, level));
        }

        // Recur for left and right subtrees
        dfs(node.left, hd - 1, level + 1, topNodes);
        dfs(node.right, hd + 1, level + 1, topNodes);
    }

    // DFS Approach to find the top view of a binary tree
    static List<Integer> topView(Node root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) return result;
        
        // Horizontal distance -> {node's value, level}
        Map<Integer, Pair<Integer, Integer>> topNodes = new TreeMap<>();

        // Start DFS traversal
        dfs(root, 0, 0, topNodes);

        // Collect nodes from the map
        for (Pair<Integer, Integer> value : topNodes.values()) {
            result.add(value.getKey());
        }

        return result;
    }

    public static void main(String[] args) {
        
        // Create a sample binary tree
        //     1
        //    / \
        //   2   3
        //  / \ / \
        // 4  5 6  7

        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.left = new Node(6);
        root.right.right = new Node(7);

        List<Integer> result = topView(root);
        for (int i : result) {
            System.out.print(i + " ");
        }
    }
}
Python
# Python program to print top view of binary tree

class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None

def dfs(node, hd, level, top_nodes):
    if not node:
        return

    # If horizontal distance is encountered for 
    # the first time or if it's at a higher level
    if hd not in top_nodes or top_nodes[hd][1] > level:
        top_nodes[hd] = (node.data, level)

    # Recur for left and right subtrees
    dfs(node.left, hd - 1, level + 1, top_nodes)
    dfs(node.right, hd + 1, level + 1, top_nodes)

# DFS Approach to find the top view of a binary tree
def topView(root):
    result = []
    if not root:
        return result
    
    # Horizontal distance -> (node's value, level)
    top_nodes = {}

    # Start DFS traversal
    dfs(root, 0, 0, top_nodes)

    # Collect nodes from the map
    for key in sorted(top_nodes):
        result.append(top_nodes[key][0])

    return result


if __name__ == "__main__":
    
    # Create a sample binary tree
    #     1
    #    / \
    #   2   3
    #  / \ / \
    # 4  5 6  7

    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)
    root.right.left = Node(6)
    root.right.right = Node(7)

    result = topView(root)
    print(" ".join(map(str, result)))
C#
// C# program to print top view of binary tree

using System;
using System.Collections.Generic;

class Node {
    public int Data;
    public Node Left, Right;

    public Node(int val) {
        Data = val;
        Left = Right = null;
    }
}

class GfG {

    // DFS Helper to store top view nodes
    static void Dfs(Node node, int hd, int level, 
                    SortedDictionary<int, Tuple<int, int>> topNodes) {
        if (node == null) return;

        // If horizontal distance is encountered for 
        // the first time or if it's at a higher level
        if (!topNodes.ContainsKey(hd) || topNodes[hd].Item2 > level) {
            topNodes[hd] = new Tuple<int, int>(node.Data, level);
        }

        // Recur for left and right subtrees
        Dfs(node.Left, hd - 1, level + 1, topNodes);
        Dfs(node.Right, hd + 1, level + 1, topNodes);
    }

    // DFS Approach to find the top view of a binary tree
    static List<int> TopView(Node root) {
        var result = new List<int>();
        if (root == null) return result;
        
        // Horizontal distance -> (node's value, level)
        var topNodes = new SortedDictionary<int, Tuple<int, int>>();

        // Start DFS traversal
        Dfs(root, 0, 0, topNodes);

        // Collect nodes from the map
        foreach (var value in topNodes.Values) {
            result.Add(value.Item1);
        }

        return result;
    }

    static void Main(string[] args) {
        
        // Create a sample binary tree
        //     1
        //    / \
        //   2   3
        //  / \ / \
        // 4  5 6  7

        Node root = new Node(1);
        root.Left = new Node(2);
        root.Right = new Node(3);
        root.Left.Left = new Node(4);
        root.Left.Right = new Node(5);
        root.Right.Left = new Node(6);
        root.Right.Right = new Node(7);

        List<int> result = TopView(root);
        Console.WriteLine(string.Join(" ", result));
    }
}
JavaScript
// JavaScript program to print top view of binary tree

class Node {
    constructor(val) {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}

function dfs(node, hd, level, topNodes) {
    if (!node) return;

    // If horizontal distance is encountered for 
    // the first time or if it's at a higher level
    if (!(hd in topNodes) || topNodes[hd][1] > level) {
        topNodes[hd] = [node.data, level];
    }

    // Recur for left and right subtrees
    dfs(node.left, hd - 1, level + 1, topNodes);
    dfs(node.right, hd + 1, level + 1, topNodes);
}

// DFS Approach to find the top view of a binary tree
function topView(root) {
    let result = [];
    if (!root) return result;
    
    // Horizontal distance -> [node's value, level]
    let topNodes = {};

    // Start DFS traversal
    dfs(root, 0, 0, topNodes);

    // Collect nodes from the map
    for (let key of Object.keys(topNodes).sort((a, b) => a - b)) {
        result.push(topNodes[key][0]);
    }

    return result;
}


const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);

const result = topView(root);
console.log(result.join(" "));

Output
4 2 1 3 7 

Using BFS – O(n * log n) Time and O(n) Space

The idea is similar to vertical Order Traversal. Like vertical Order Traversal, we need to put nodes of the same horizontal distance together. We do a level order traversal so that the topmost node at a horizontal distance is visited before any other node of the same horizontal distance below it. HashMap is used to check if a node at a given horizontal distance is seen or not. Set the hd of the root to zero and push it into the queue. While the queue is not empty, pop the front element and check its horizontal distance. If it has not been encountered before, add the node’s value to the map at that horizontal distance. Then, for each child of the current node, set its hd as root->hd – 1 for the left child and root->hd + 1 for the right child, and push them into the queue. Continue this process until the queue is empty. Finally, return the values stored in the map to display the top view of the binary tree.

C++
// C++ program to print top
// view of binary tree

#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;   
    Node* left;
    Node* right;

    Node(int val) {
        data = val;
        left = right = nullptr;
    }
};

// Function to return the top view of a binary tree
vector<int> topView(Node *root) {
    vector<int> result;
    if (!root) return result;

    // Map to store the first node at each 
      // horizontal distance (hd)
    map<int, int> topNodes;
    
    // Queue to store nodes along with their horizontal distance
    queue<pair<Node*, int>> q;

    // Start BFS with the root node at horizontal distance 0
    q.push({root, 0});

    while (!q.empty()) {
        
        auto nodeHd = q.front();
        
        // Current node
        Node *node = nodeHd.first;  
        
        // Current horizontal distance
        int hd = nodeHd.second;     
        q.pop();

        // If this horizontal distance is seen for the first
          // time, store the node
        if (topNodes.find(hd) == topNodes.end()) {
            topNodes[hd] = node->data;
        }

        // Add left child to the queue with horizontal
          // distance - 1
        if (node->left) {
            q.push({node->left, hd - 1});
        }

        // Add right child to the queue with horizontal distance + 1
        if (node->right) {
            q.push({node->right, hd + 1});
        }
    }

    // Extract the nodes from the map in sorted order 
      // of their horizontal distances
    for (auto it : topNodes) {
        result.push_back(it.second);
    }

    return result;
}


int main() {
    
    // Create a sample binary tree
    //     1
    //    / \
    //   2   3
    //  / \ / \
    // 4  5 6  7

    Node* root = new Node(1);
    root->left = new Node(2);       
    root->right = new Node(3);            
    root->left->left = new Node(4);     
    root->left->right = new Node(5);   
    root->right->left = new Node(6);   
    root->right->right = new Node(7); 

    vector<int> result = topView(root);
    for (int i : result) {
        cout << i << " ";
    }
    return 0;
}
Java
// Java program to print top
// view of binary tree

import java.util.*;

class Node {
    int data;
    Node left, right;

    Node(int val) {
        data = val;
        left = right = null;
    }
}

// Function to return the top view of a binary tree
class GfG {

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

        // Map to store the first node at each 
          // horizontal distance (hd)
        Map<Integer, Integer> topNodes = new TreeMap<>();

        // Queue to store nodes along with their horizontal distance
        Queue<Map.Entry<Node, Integer>> q = new LinkedList<>();

        // Start BFS with the root node at horizontal distance 0
        q.add(new AbstractMap.SimpleEntry<>(root, 0));

        while (!q.isEmpty()) {
            Map.Entry<Node, Integer> nodeHd = q.poll();

            // Current node
            Node node = nodeHd.getKey();

            // Current horizontal distance
            int hd = nodeHd.getValue();

            // If this horizontal distance is seen for
              // the first time, store the node
            if (!topNodes.containsKey(hd)) {
                topNodes.put(hd, node.data);
            }

            // Add left child to the queue with horizontal distance - 1
            if (node.left != null) {
                q.add(new AbstractMap.SimpleEntry<>(node.left, hd - 1));
            }

            // Add right child to the queue with horizontal
              // distance + 1
            if (node.right != null) {
                q.add(new AbstractMap.SimpleEntry<>(node.right, hd + 1));
            }
        }

        // Extract the nodes from the map in sorted order
          // of their horizontal distances
        for (Integer value : topNodes.values()) {
            result.add(value);
        }

        return result;
    }

    public static void main(String[] args) {

        // Create a sample binary tree
        //     1
        //    / \
        //   2   3
        //  / \ / \
        // 4  5 6  7

        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        root.right.left = new Node(6);
        root.right.right = new Node(7);

        List<Integer> result = topView(root);
           for (int i : result) {
            System.out.print(i + " ");
        }
    }
}
Python
# Python program to print top
# view of binary tree

from collections import deque

class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None

# Function to return the top view of
# a binary tree
def topView(root):
    result = []
    if not root:
        return result

    # Map to store the first node at each
    # horizontal distance (hd)
    topNodes = {}

    # Queue to store nodes along with their horizontal distance
    q = deque([(root, 0)])

    # Start BFS with the root node at horizontal distance 0
    while q:
        node, hd = q.popleft()

        # If this horizontal distance is seen for the 
        # first time, store the node
        if hd not in topNodes:
            topNodes[hd] = node.data

        # Add left child to the queue with horizontal
        # distance - 1
        if node.left:
            q.append((node.left, hd - 1))

        # Add right child to the queue with horizontal
        # distance + 1
        if node.right:
            q.append((node.right, hd + 1))

    # Extract the nodes from the map in sorted order of
    # their horizontal distances
    for key in sorted(topNodes.keys()):
        result.append(topNodes[key])

    return result
    

if __name__ == "__main__":

    # Create a sample binary tree
    #     1
    #    / \
    #   2   3
    #  / \ / \
    # 4  5 6  7

    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)
    root.right.left = Node(6)
    root.right.right = Node(7)

    result = topView(root)
    print(" ".join(map(str, result)))
C#
// C# program to print top
// view of binary tree
using System;
using System.Collections.Generic;

class Node {
    public int Data;
    public Node Left, Right;

    public Node(int val) {
        Data = val;
        Left = Right = null;
    }
}

class GfG {
  
    // Function to return the top view of a binary tree
    static List<int> TopView(Node root) {
        List<int> result = new List<int>();
        if (root == null)
            return result;

        // Map to store the first node at each horizontal
        // distance (hd)
        SortedDictionary<int, int> topNodes
            = new SortedDictionary<int, int>();

        // Queue to store nodes along with their horizontal
        // distance
        Queue<KeyValuePair<Node, int> > q
            = new Queue<KeyValuePair<Node, int> >();

        // Start BFS with the root node at horizontal
        // distance 0
        q.Enqueue(new KeyValuePair<Node, int>(root, 0));

        while (q.Count > 0) {
            var nodeHd = q.Dequeue();

            // Current node
            Node node = nodeHd.Key;

            // Current horizontal distance
            int hd = nodeHd.Value;

            // If this horizontal distance is seen for the
            // first time, store the node
            if (!topNodes.ContainsKey(hd)) {
                topNodes[hd] = node.Data;
            }

            // Add left child to the queue with horizontal
            // distance - 1
            if (node.Left != null) {
                q.Enqueue(new KeyValuePair<Node, int>(
                    node.Left, hd - 1));
            }

            // Add right child to the queue with horizontal
            // distance + 1
            if (node.Right != null) {
                q.Enqueue(new KeyValuePair<Node, int>(
                    node.Right, hd + 1));
            }
        }

        // Extract the nodes from the map in sorted order of
        // their horizontal distances
        foreach(var item in topNodes) {
            result.Add(item.Value);
        }

        return result;
    }

    static void Main(string[] args) {
      
        // Create a sample binary tree
        //     1
        //    / \
        //   2   3
        //  / \ / \
        // 4  5 6  7

        Node root = new Node(1);
        root.Left = new Node(2);
        root.Right = new Node(3);
        root.Left.Left = new Node(4);
        root.Left.Right = new Node(5);
        root.Right.Left = new Node(6);
        root.Right.Right = new Node(7);

        List<int> result = TopView(root);

        foreach(int val in result) {
            Console.Write(val + " ");
        }
    }
}
JavaScript
// JavaScript program to print top
// view of binary tree

class Node {
    constructor(val) {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}

// Function to return the top view of
// a binary tree
function topView(root) {
    let result = [];
    if (!root) return result;

    // Map to store the first node at each 
    // horizontal distance (hd)
    let topNodes = new Map();

    // Queue to store nodes along with their
    // horizontal distance
    let q = [];
    q.push([root, 0]);

    // Start BFS with the root node at horizontal distance 0
    while (q.length > 0) {
        let [node, hd] = q.shift();

        // If this horizontal distance is seen for the
        // first time, store the node
        if (!topNodes.has(hd)) {
            topNodes.set(hd, node.data);
        }

        // Add left child to the queue with horizontal
        // distance - 1
        if (node.left) {
            q.push([node.left, hd - 1]);
        }

        // Add right child to the queue with horizontal
        // distance + 1
        if (node.right) {
            q.push([node.right, hd + 1]);
        }
    }

    // Extract the nodes from the map in sorted order of their
    // horizontal distances
    for (let [key, value] of [...topNodes.entries()].sort((a, b) => a[0] - b[0])) {
        result.push(value);
    }

    return result;
}

// Create a sample binary tree
//     1
//    / \
//   2   3
//  / \ / \
// 4  5 6  7

let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);

let result = topView(root);
console.log(result.join(" "));

Output
4 2 1 3 7 


Previous Article
Next Article

Similar Reads

three90RightbarBannerImg