Print nodes in the Top View of Binary Tree | Set 3

Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Given a binary tree, print the top view of it. The output nodes can be printed in any order. Expected time complexity is O(n)

A node x is there in output if x is the topmost node at its horizontal distance. Horizontal distance of left child of a node x is equal to horizontal distance of x minus 1, and that of right child is horizontal distance of x plus 1.
Example :

       1
    /     \
   2       3
  /  \    / \
 4    5  6   7
Top view of the above binary tree is
4 2 1 3 7

        1
      /   \
    2       3
      \   
        4  
          \
            5
             \
               6
Top view of the above binary tree is
2 1 3 6

Approach:

  • The idea here is to observe that, if we try to see a tree from its top, then only the nodes which are at top in vertical order will be seen.
  • Start BFS from root. Maintain a queue of pairs comprising of node(Node *) type and vertical distance of node from root. Also, maintain a map which should store the node at a particular vertical distance.
  • While processing a node, just check if any node is there in the map at that vertical distance.
  • If any node is there, it means the node can’t be seen from top, do not consider it. Else, if there is no node at that vertical distance, store that in map and consider for top view.

Below is the implementation based on above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to print top
// view of binary tree
#include <bits/stdc++.h>
using namespace std;
  
// Structure of binary tree
struct Node {
    Node* left;
    Node* right;
    int data;
};
  
// function to create a new node
Node* newNode(int key)
{
    Node* node = new Node();
    node->left = node->right = NULL;
    node->data = key;
    return node;
}
  
// function should print the topView of
// the binary tree
void topView(struct Node* root)
{
    // Base case
    if (root == NULL) {
        return;
    }
  
    // Take a temporary node
    Node* temp = NULL;
  
    // Queue to do BFS
    queue<pair<Node*, int> > q;
  
    // map to store node at each vartical distance
    map<int, int> mp;
  
    q.push({ root, 0 });
  
    // BFS
    while (!q.empty()) {
  
        temp = q.front().first;
        int d = q.front().second;
        q.pop();
  
        // If any node is not at that vertical distance
        // just insert that node in map and print it
        if (mp.find(d) == mp.end()) {
            cout << temp->data << " ";
            mp[d] = temp->data;
        }
  
        // Continue for left node
        if (temp->left) {
            q.push({ temp->left, d - 1 });
        }
  
        // Continue for right node
        if (temp->right) {
            q.push({ temp->right, d + 1 });
        }
    }
}
  
// Driver Program to test above functions
int main()
{
    /* Create following Binary Tree 
         
        / \ 
        2 3 
        
         
          
           
            
             6*/
    Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->right = newNode(4);
    root->left->right->right = newNode(5);
    root->left->right->right->right = newNode(6);
    cout << "Following are nodes in top view of Binary Tree\n";
    topView(root);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

   
// Java  program to print top
// view of binary tree
import java.util.*;
class solution
{
  
// structure of binary tree
static class Node {
    Node left;
    Node right;
    int data;
};
  
// structure of pair
static class Pair {
    Node first;
    int second;
    Pair(Node n,int a)
    {
        first=n;
        second=a;
    }
};
  
// function to create a new node
static Node newNode(int key)
{
    Node node = new Node();
    node.left = node.right = null;
    node.data = key;
    return node;
}
  
// function should print the topView of
// the binary tree
static void topView( Node root)
{
    // Base case
    if (root == null) {
        return;
    }
  
    // Take a temporary node
    Node temp = null;
  
    // Queue to do BFS
    Queue<Pair > q =  new LinkedList<Pair>();
  
    // map to store node at each vartical distance
    Map<Integer, Integer> mp = new HashMap<Integer, Integer>();
  
    q.add(new Pair( root, 0 ));
  
    // BFS
    while (q.size()>0) {
  
        temp = q.peek().first;
        int d = q.peek().second;
        q.remove();
  
        // If any node is not at that vertical distance
        // just insert that node in map and print it
        if (mp.get(d) == null) {
            System.out.print( temp.data + " ");
            mp.put(d, temp.data);
        }
  
        // Continue for left node
        if (temp.left!=null) {
            q.add(new Pair( temp.left, d - 1 ));
        }
  
        // Continue for right node
        if (temp.right!=null) {
            q.add(new Pair( temp.right, d + 1 ));
        }
    }
}
  
// Driver Program to test above functions
public static void main(String args[])
{
    /* Create following Binary Tree 
         
        / \ 
        2 3 
        
         
          
           
            
             6*/
    Node root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(3);
    root.left.right = newNode(4);
    root.left.right.right = newNode(5);
    root.left.right.right.right = newNode(6);
    System.out.println( "Following are nodes in top view of Binary Tree\n");
    topView(root);
}
}
//contributed by Arnab Kundu

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to print top
// view of binary tree
using System; 
using System.Collections.Generic; 
  
class GFG
{
  
// structure of binary tree
public class Node 
{
    public Node left;
    public Node right;
    public int data;
};
  
// structure of pair
public class Pair 
{
    public Node first;
    public int second;
    public Pair(Node n,int a)
    {
        first = n;
        second = a;
    }
};
  
// function to create a new node
static Node newNode(int key)
{
    Node node = new Node();
    node.left = node.right = null;
    node.data = key;
    return node;
}
  
// function should print the topView of
// the binary tree
static void topView( Node root)
{
    // Base case
    if (root == null)
    {
        return;
    }
  
    // Take a temporary node
    Node temp = null;
  
    // Queue to do BFS
    Queue<Pair > q = new Queue<Pair>();
  
    // map to store node at each vartical distance
    Dictionary<int, int> mp = new Dictionary<int, int>();
  
    q.Enqueue(new Pair( root, 0 ));
  
    // BFS
    while (q.Count>0) 
    {
  
        temp = q.Peek().first;
        int d = q.Peek().second;
        q.Dequeue();
  
        // If any node is not at that vertical distance
        // just insert that node in map and print it
        if (!mp.ContainsKey(d)) 
        {
            Console.Write( temp.data + " ");
            mp.Add(d, temp.data);
        }
  
        // Continue for left node
        if (temp.left != null
        {
            q.Enqueue(new Pair( temp.left, d - 1 ));
        }
  
        // Continue for right node
        if (temp.right != null)
        {
            q.Enqueue(new Pair( temp.right, d + 1 ));
        }
    }
}
  
// Driver code
public static void Main(String []args)
{
    /* Create following Binary Tree 
        
        / \ 
        2 3 
        
        
        
        
            
            6*/
    Node root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(3);
    root.left.right = newNode(4);
    root.left.right.right = newNode(5);
    root.left.right.right.right = newNode(6);
    Console.Write( "Following are nodes in top view of Binary Tree\n");
    topView(root);
}
}
  
/* This code contributed by PrinciRaj1992 */

chevron_right


Output:

Following are nodes in top view of Binary Tree
1 2 3 6


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : andrew1234, princiraj1992



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.