VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-nodes-odd-levels-tree/

⇱ Nodes at odd levels of a tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Nodes at odd levels of a tree

Last Updated : 17 May, 2026

Given a binary tree, The task is to return nodes in sorted order. root is considered at level 1.

Examples:

Input: root = [1, 2, 3, 4, 5, N, 6, N, N, 7, 8, 9]

👁 2056957992

Output: [1, 4, 5, 6]
Explanation: Nodes at odd levels (1 and 3) are 1, 4, 5, 6, which are collected and returned in sorted order.

Input: root = [1, 2, 3, 4, 5, N, 6]

👁 2056957997

Output: [1, 4, 5, 6]
Explanation: Nodes at odd levels (1 and 3) are 1, 4, 5, 6, which are collected and returned in sorted order.

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.

Output
1 4 5 6 

Time complexity: O(n log n) 
Auxiliary Space: O(n)

Comment
Article Tags: