Skip to content

Instantly share code, notes, and snippets.

@shubham100795
Last active February 22, 2017 14:13
Show Gist options
  • Select an option

  • Save shubham100795/87aae1f4ef19ead0118b5618616a1f12 to your computer and use it in GitHub Desktop.

Select an option

Save shubham100795/87aae1f4ef19ead0118b5618616a1f12 to your computer and use it in GitHub Desktop.
Top View of BST using STL library
#include<iostream>
#include<cstdlib>
#include<queue>
#include<map>
using namespace std;
struct node{
int data;
struct node *left;
struct node *right;
};
class qitem{
public:
struct node *tnode;
int hd;
qitem(struct node *n,int x)
{
tnode=n;
hd=x;
}
};
struct node *newnode(int x)
{
struct node* ptr=(struct node*)malloc(sizeof(struct node));
ptr->data=x;
ptr->left=NULL;
ptr->right=NULL;
return ptr;
}
struct node* insert(struct node *root,int x)
{
struct node* par;
if(root==NULL)
{
root=newnode(x);
return root;
}
else
{
struct node *proot=root;
while(proot!=NULL)
{
if(x<proot->data)
{
par=proot;
proot=proot->left;
}
else
{
par=proot;
proot=proot->right;
}
}
if(x<par->data)
par->left=newnode(x);
else
par->right=newnode(x);
return root;
}
}
void display(struct node *root)
{
if(root==NULL)
return;
display(root->left);
cout<<"\t"<<root->data;
display(root->right);
}
void topview(struct node *root,map<int,int> &m)
{
queue<qitem*> q;
if(root==NULL)
return;
q.push(new qitem(root,0));
while(!q.empty())
{
qitem *element=q.front();
int d=element->hd;
struct node *n=element->tnode;
q.pop();
if(m.count(d)==0)
m[d]=n->data;
if(n->left)
{
q.push(new qitem(n->left,d-1));
}
if(n->right)
{
q.push(new qitem(n->right,d+1));
}
}
}
int main()
{
int x;
map<int,int> mp;
map<int,int>::iterator it;
struct node *root=NULL;
while(1)
{
cin>>x;
if(x==-1)
break;
root=insert(root,x);
}
display(root);
cout<<endl;
topview(root,mp);
for(it=mp.begin();it!=mp.end();it++)
{
cout<<"\t"<<it->second;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment