-
Notifications
You must be signed in to change notification settings - Fork 0
/
topViewOfTree.cpp
70 lines (62 loc) · 1.33 KB
/
topViewOfTree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//Note: In printing topview of a tree,among the Nodes at the same horizontol distance
//the one that is encountered first while traversal is printed.
#include<iostream>
#include<queue>
#include<vector>
#include <map>
using namespace std;
struct Node
{
int key;
Node* left,*right;
};
void topView(Node* root)
{
if(root==NULL)
return;
unordered_map<int, int> m;
queue<pair<Node*, int> > q;
q.push(make_pair(root,0));
while(!q.empty())
{
pair<Node*, int> p=q.front();
Node* n=p.first;
int val=p.second; //val is the horizontol distance
q.pop();
// if horizontal value is not in the hashmap
// that means it is the first value with that
// horizontal distance so print it and store
// this value in hashmap
if(m.find(val)==m.end())
{
m[val]=n->key;
cout<<n->key<<" ";
}
if(n->left!=NULL)
{
q.push(make_pair(n->left,val-1));
}
if(n->right!=NULL)
{
q.push(make_pair(n->right,val+1));
}
}
}
Node* newNode(int key)
{
Node* node=new Node;
node->key=key;
node->left=node->right=NULL;
return node;
}
int main()
{
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);
topView(root);
return 0;
}