[Approach] Iterative Approach - O(n) Time and O(n) Space
The idea is to traverse the binary tree using level order traversal. For each level, print the left extreme node or right extreme node based on the level.
Step by step approach:
Create a queue and insert the root node into it.
Initialize a boolean variable rightExtreme and set it to true to indicate that the right extreme node is required first.
For each level, determine the number of nodes currently present in the queue.
Traverse all nodes of that level one by one.
During traversal, treat the first node as the extreme left and the last node as the extreme right.
If rightExtreme is true, append the right extreme node; otherwise, append the left extreme node.
Toggle the value of rightExtreme after processing each level.