Tree:Top view javascript solution code example
Example: gfg top view of tree
class Obj
{
public:
Node *root;
int dis;
Obj(Node *node, int dist)
{
root = node;
dis = dist;
}
};
void topView(Node *root)
{
queue<Obj*> q;
q.push(new Obj(root, 0));
map<int,int> m;
while(!q.empty())
{
Obj *ob = q.front();
q.pop();
if(m.find(ob->dis) == m.end())
m[ob->dis] = ob->root->data;
if(ob->root->left != NULL)
q.push(new Obj(ob->root->left, ob->dis-1));
if(ob->root->right != NULL)
q.push(new Obj(ob->root->right, ob->dis+1));
}
for(auto it=m.begin(); it!=m.end(); it++)
cout << it->second << "\t";
cout << endl;
}