Right View of Binary Tree

 Given a Binary Tree, find Right view of it. Right view of a Binary Tree is set of nodes visible when tree is viewed from right side.

Right view of following tree is 1 3 7 8.

          1
       /     \
     2        3
   /   \      /    \
  4     5   6    7
    \
     8

Example 1:

Input:
       1
    /    \
   3      2
Output: 1 2

Example 2:

Input:
     10
    /   \
  20     30
 /   \
40  60 
Output: 10 30 60


method:

 

c++ implementation:

void rightView(Node *root)
{  queue<Node*> q;
  
    if (root == NULL) 
        return; 
    q.push(root); 
    q.push(NULL); 

    while (!q.empty()) { 
        Node* temp = q.front(); 

        if (temp) { 
            cout<< temp->data<<" ";
            while (q.front() != NULL) { 
                if (temp->right) 
                    q.push(temp->right); 
                if (temp->left) 
                    q.push(temp->left); 
                q.pop(); 

                temp = q.front(); 
            } 
            q.push(NULL);
            
        } 
        q.pop(); 
    } 
}


Time Complexity: O(n) 



No comments

darkmode