Open In App

Print Nodes in Top View of Binary Tree

Last Updated : 23 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

top_view_example1


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

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

Top view for example 2

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. We keep track of horizontal distance from root node. Start from the root node with a distance of 0. When we move to left child we subtract 1 and add 1 when we move to right child to distance of the current node. We use a HashMap to store the top most node that appears at a given horizontal distance. As we traverse the tree, we check if there is any node at current distance in hashmap . If it’s the first node encountered at its horizontal distance ,we include it in the top view.

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

#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
// using dfs
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 ArrayList<Integer> topView(Node root) {
        ArrayList<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);

        ArrayList<Integer> result = topView(root);
        for (int i : result) {
            System.out.print(i + " ");
        }
    }
}
Python
# Python program to print 
# top view of binary tree
# using dfs
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 dfs
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
// using dfs
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;
}

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

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 just do a level order traversal (bfs) instead of dfs so that the topmost node at a horizontal distance is visited before any other node of the same horizontal distance below it.

C++
// C++ program to print top
// view of binary tree
// using bfs
#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
// using bfs
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 ArrayList<Integer> topView(Node root) {
        ArrayList<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);

        ArrayList<Integer> result = topView(root);
       	for (int i : result) {
            System.out.print(i + " ");
        }
    }
}
Python
# Python program to print top
# view of binary tree
# using bfs
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 bfs
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
// using bfs
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;
}

//driver code
// 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 

Optimized Approach Using BFS – O(n) Time and O(n) Space

A queue is used to perform level-order traversal, storing each node along with its corresponding horizontal distance from the root. hashmap keeps track of the topmost node at every horizontal distance. During traversal, if a node at a given horizontal distance is encountered for the first time, it is added to the map.

Additionally, the minimum horizontal distance (mn) is updated to organize the result. After completing the traversal, the map’s values are transferred to a result array, adjusting indices based on mn to ensure the nodes are arranged correctly from leftmost to rightmost in the top view. BFS approach ensures that nodes closer to the root and encountered first are prioritized in the top view.

C++
// C++ program to print top view of binary tree
// optimally using bfs

#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 a list of nodes visible
// from the top view from left to right in Binary Tree.
vector<int> topView(Node *root) {
  
    // base case
    if (root ==  nullptr) {
        return {};
    }
    Node *temp = nullptr;
  
    // creating empty queue for level order traversal.
    queue<pair<Node *, int>> q;
  
    // creating a map to store nodes at a
    // particular horizontal distance.
    unordered_map<int, int> mp;

    int mn = INT_MAX;
    q.push({root, 0});
    while (!q.empty()) {
      
        temp = q.front().first;
        int d = q.front().second;
        mn = min(mn, d);
        q.pop();
      
        // storing temp->data in map.
        if (mp.find(d) == mp.end()) {
            mp[d] = temp->data;
        }
      
        // if left child of temp exists, pushing it in
        // the queue with the horizontal distance.
        if (temp->left) {
            q.push({temp->left, d - 1});
        }
      
        // if right child of temp exists, pushing it in
        // the queue with the horizontal distance.
        if (temp->right) {
            q.push({temp->right, d + 1});
        }
    }
    vector<int> ans(mp.size());
  
    // traversing the map and storing the nodes in list
    // at every horizontal distance.
    for (auto it = mp.begin(); it != mp.end(); it++) {
        ans[it->first - mn] = (it->second);
    }
  
    return ans;
}

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
// optimally using bfs
import java.util.*;

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

class GfG {
  
    // Function to return a list of nodes visible from the
    // top view from left to right in Binary Tree.
    static ArrayList<Integer> topView(Node root) {
      
        // Base case: if the tree is empty, return an empty
        // list
        if (root == null) {
            return new ArrayList<>();
        }
      
        // Queue to perform level order traversal.
        // Each element in the queue is a pair of (Node,
        // horizontal distance)
        Queue<Pair> queue = new LinkedList<>();
        queue.add(new Pair(root, 0));
      
        // HashMap to store the first node at each
        // horizontal distance
        HashMap<Integer, Integer> map = new HashMap<>();
      
        // Variables to track the minimum and maximum
        // horizontal distances
        int minHD = 0;
        int maxHD = 0;
        while (!queue.isEmpty()) {
            Pair current = queue.poll();
            Node currentNode = current.node;
            int hd = current.dist;
          
            // Update min and max horizontal distances
            if (hd < minHD) {
                minHD = hd;
            }
            if (hd > maxHD) {
                maxHD = hd;
            }
          
            // If a horizontal distance is encountered for
            // the first time, add it to the map
            if (!map.containsKey(hd)) {
                map.put(hd, currentNode.data);
            }
          
            // Enqueue the left child with horizontal
            // distance hd - 1
            if (currentNode.left != null) {
                queue.add(
                    new Pair(currentNode.left, hd - 1));
            }
          
            // Enqueue the right child with horizontal
            // distance hd + 1
            if (currentNode.right != null) {
                queue.add(
                    new Pair(currentNode.right, hd + 1));
            }
        }
      
        // Prepare the result list by traversing from minHD
        // to maxHD
        ArrayList<Integer> topViewList = new ArrayList<>();
        for (int hd = minHD; hd <= maxHD; hd++) {
            if (map.containsKey(hd)) {
                topViewList.add(map.get(hd));
            }
        }
        return topViewList;
    }

    // Helper class to store a node along with its
    // horizontal distance
    static class Pair {
        Node node;
        int dist;
        Pair(Node node, int dist) {
            this.node = node;
            this.dist = dist;
        }
    }
  
    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);

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

from queue import Queue

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

# Function to return a list of nodes visible
# from the top view from left to right in Binary Tree.

def topView(root):
  
    # base case
    if not root:
        return []

    temp = None
    
    # creating empty queue for level order traversal.
    q = Queue()
    
    # creating a dictionary to store nodes at a
    # particular horizontal distance.
    mp = {}

    mn = float('inf')
    q.put((root, 0))
    while not q.empty():
        temp, d = q.get()
        mn = min(mn, d)
        
        # storing temp.data in dictionary.
        if d not in mp:
            mp[d] = temp.data
            
        # if left child of temp exists, pushing it in
        # the queue with the horizontal distance.
        if temp.left:
            q.put((temp.left, d - 1))
            
        # if right child of temp exists, pushing it in
        # the queue with the horizontal distance.
        if temp.right:
            q.put((temp.right, d + 1))
            
    # Initialize result array with size equal to dictionary size
    ans = [0] * len(mp)
    
    # Fill result array based on horizontal distances
    for d, value in mp.items():
        ans[d - mn] = value
    return ans


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
// optimally using bfs
using System;
using System.Collections.Generic;
using System.Linq;

class Node {
    public int data;
    public Node left, right;

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

class GfG {
  
    // Function to return a list of nodes visible
    // from the top view from left to right in Binary Tree.
    public static List<int> TopView(Node root) {

        // base case
        if (root == null)
            return new List<int>();

        Node temp = null;
      
        // creating empty queue for level order traversal.
        Queue<(Node, int)> q = new Queue<(Node, int)>();
      
        // creating a dictionary to store nodes at a
        // particular horizontal distance.
        Dictionary<int, int> mp
            = new Dictionary<int, int>();

        int mn = int.MaxValue;
        q.Enqueue((root, 0));

        while (q.Count > 0) {
            var front = q.Dequeue();
            temp = front.Item1;
            int d = front.Item2;
            mn = Math.Min(mn, d);

            // storing temp.data in dictionary.
            if (!mp.ContainsKey(d)) {
                mp[d] = temp.data;
            }

            // if left child of temp exists, pushing it in
            // the queue with the horizontal distance.
            if (temp.left != null) {
                q.Enqueue((temp.left, d - 1));
            }
          
            // if right child of temp exists, pushing it in
            // the queue with the horizontal distance.
            if (temp.right != null) {
                q.Enqueue((temp.right, d + 1));
            }
        }

        // Initialize result array with size equal to
        // dictionary size
        List<int> ans = new List<int>(new int[mp.Count]);
      
        // Fill result array based on horizontal distances
        foreach(var entry in mp) {
            ans[entry.Key - mn] = entry.Value;
        }

        return ans;
    }

    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
// optimally using bfs

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

function topView(root) {

    // Base case
    if (root === null) {
        return [];
    }

    // Queue for level order traversal
    let queue = [];
    
    // Map to store nodes at a particular horizontal
    // distance
    let map = new Map();

    // Track the minimum horizontal distance
    let minDistance = Number.MAX_VALUE;

    // Start with the root at horizontal distance 0
    queue.push([ root, 0 ]);

    while (queue.length > 0) {
        let [temp, d] = queue.shift();

        // Update the minimum horizontal distance
        minDistance = Math.min(minDistance, d);

        // If the horizontal distance is not yet in the map,
        // add it
        if (!map.has(d)) {
            map.set(d, temp.data);
        }

        // Add left child with horizontal distance d - 1
        if (temp.left) {
            queue.push([ temp.left, d - 1 ]);
        }

        // Add right child with horizontal distance d + 1
        if (temp.right) {
            queue.push([ temp.right, d + 1 ]);
        }
    }

    // Create the result array with size equal to map size
    let ans = new Array(map.size);

    // Populate the result array using the map
    for (let [key, value] of map) {
        ans[key - minDistance] = value;
    }

    return ans;
}

// Driver code
// 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 


Next Article

Similar Reads