Using Recursive Approach- O(n log n) Time O(n) Space
The idea is to recursively traverse the binary tree while keeping track of the current level using a boolean flag, collect nodes that lie on odd levels, and finally sort the collected nodes before returning the result.
Working of Approach:
Start from root (level 1 -> odd), add 1 to result.
Move to level 2 (even), skip nodes 2, 3.
Move to level 3 (odd), add 4, 5, 6 to result.
Continue traversal but skip level 4 nodes 7, 8, 9.
Final collected nodes -> [1,4,5,6], sort and return.
Output
1 4 5 6
Time complexity: O(n log n) Auxiliary Space: O(n)
Using Iterative Approach - O(n log n) Time O(n) Space
The idea is to perform level order traversal using a queue, track levels using a boolean flag, collect nodes at odd levels, and finally sort the collected nodes before returning the result.
Working of Approach:
Initialize queue with root and mark level as odd.
Process level 1 -> add 1, push children 2, 3.
Process level 2 -> skip 2, 3, push their children.
Process level 3 -> add 4, 5, 6, push next level nodes.
Final collected nodes -> [1,4,5,6], sort and return.