
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print Nodes in the Top View of Binary Tree Using C++
In this tutorial, we will be discussing a program to print all the nodes that appear in the top view of a given binary tree.
For a particular binary tree, a node appears in its top view if it is the very first node at its horizontal distance. Horizontal distance for the left node of a node x is x-1 and for the right node of node x is x+1.
To solve this, we will do the level order traversal so that we get the topmost node for a particular level before the other nodes present at that level. Further, we will use hashing to check whether the selected node is visible in the top view or not.
Example
#include <iostream> #include<queue> #include<map> using namespace std; struct Node{ Node * left; Node* right; int h_dist; int data; }; Node* create_node(int key){ Node* node=new Node(); node->left = node->right = NULL; node->data=key; return node; } void print_topview(Node* root){ if(root==NULL) return; queue<Node*>q; map<int,int> m; int h_dist=0; root->h_dist=h_dist; q.push(root); cout<< "Top View for the given tree:" << endl; while(q.size()){ h_dist=root->h_dist; if(m.count(h_dist)==0) m[h_dist]=root->data; if(root->left){ root->left->h_dist=h_dist-1; q.push(root->left); } if(root->right){ root->right->h_dist=h_dist+1; q.push(root->right); } q.pop(); root=q.front(); } for(auto i=m.begin();i!=m.end();i++){ cout<<i->second<< " "; } } int main(){ Node* root = create_node(11); root->left = create_node(23); root->right = create_node(35); root->left->right = create_node(47); root->left->right->right = create_node(59); root->left->right->right->right = create_node(68); print_topview(root); return 0; }
Output
Top View for the given tree: 23 11 35 68
Advertisements