gfg right view of tree

Solutions on MaxInterview for gfg right view of tree by the best coders in the world

showing results for - "gfg right view of tree"
Mitzi
09 Nov 2020
1/* This is not the entire code. It's just the function which implements 
2   bottom view. You need to write required code. */
3
4// Obj class is used to store node with it's distance from parent.
5class Obj
6{
7    public:
8        Node *root;
9        int dis; // distance from parent node. distance of root node will be 0.
10
11        Obj(Node *node, int dist)
12        {
13            root = node;
14            dis = dist;
15        }
16};
17
18// function to print right view.
19void rightView(Node *root)
20{
21    queue<Obj*> q;
22    q.push(new Obj(root, 0));
23    map<int,int> m;
24
25    while(!q.empty())
26    {
27        Obj *ob = q.front();
28        q.pop();
29
30        m[ob->dis] = ob->root->data;
31
32        if(ob->root->left != NULL)
33            q.push(new Obj(ob->root->left, ob->dis+1)); 
34        if(ob->root->right != NULL)
35            q.push(new Obj(ob->root->right, ob->dis+1));
36    }
37
38    for(auto it=m.begin(); it!=m.end(); it++)
39        cout << it->second << "\t";
40
41    cout << endl;
42}