![]() |
VOOZH | about |
Given a Generic Tree consisting of N nodes, the task is to find the left and right views of the given generic Tree.
Examples:
Input:
1
/ \
2 3
/ \ / \ \
4 5 6 7 8Output:
Left View: 1 2 4
Right View: 1 3 8
Explanation:
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.Input:
1
/ \
2 3
\ / \
4 5 6
\
7
Output:
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)