Left and Right view of a Generic Tree
/ \ / \ \
4 5 6 7 8
Left View: 1 2 4
Right View: 1 3 8
When the tree is viewed from the left side, then the nodes which are visible is 1 2 4.
When the tree is viewed from the right side, then the nodes which are visible is 1 3 8.
\ / \
4 5 6
Left View: 1 2 4 7
Right View: 1 3 6 7
Approach: The given problem can be solved by using the concept of Level order traversal of the tree. In this, traversal of the tree is done in level ordered fashion. After storing all the nodes in the level order traversal, it is clear that in the left view of the tree is the first node of all the levels and similarly right view of the tree is the last node of all the levels starting from the root.
Therefore, after storing the level order traversal first print all the first nodes stored in each level for the Left View and print all the last nodes stored in each level for the Right View.
Below is the implementation of the above approach:
Left View: 1 2 4 RIght View: 1 3 8
Time Complexity: O(N)
Auxiliary Space: O(N)