We are given a Binary Tree, Print the Right view of Binary tree,

Right view of binary tree is : List of all nodes which are visible If you look at Binary tree from right side.

For example,

Right view of following tree is a, c, g, h a / \ b c / \ / \ d e f g \ h

Hint for logic :

## First Simple Method for Right view of Binary Tree:

- Traverse the Binary tree from right to left
- Print the first “node->data” you encounter
- Take two variables , currentLevel=0 and nextLevel=1
- when you change level , change the currentLevel = nextLevel
- Print node->data only when current level<nextLevel to print only the first element in the right.
- For rest of the nodes on the the level currentLevel and nextLevel are equal so it wont print.

## Second Method : Level Order Traversal for Right view of Binary Tree:

If you Print a Tree in breadth first search manner, then it will print

a, b, c, d, e, f, g, h, now the list of nodes we visit the last in each breadth is required list.

Lets Code given problem

**Recursive way**

void rightViewUtil(struct Node *node, int bredth, int *m_l){ if (node==NULL) return; // Check If current node is the last one of its level/breadth if (*m_l < bredth){ printf("%d\t", node->data); *m_l = bredth; } // Recursion for right subtree and then left subtree rightViewUtil(node->right, bredth+1, m_l); rightViewUtil(node->left, bredth+1, m_l); } void rightView(struct Node *node){ int max_level = 0; rightViewUtil(node, 1, &max_level); }

Time Complexity : O(n)

Space Complexity : O(1) if you don’t consider stack space utilized by Recursion.

[…] Right View of a Binary Tree, its edge cases and failing cases to handle in code Solution : http://gohired.in/2016/07/24/right-view-of-binary-tree/ […]