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.

Try It Yourself
redirect icon

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.
C++
#include <bits/stdc++.h>
using namespace std;

class Node
{
  public:
    int data;
    Node *left;
    Node *right;

    Node(int val)
    {
        data = val;
        left = nullptr;
        right = nullptr;
    }
};

void solve(Node *root, bool isOdd, vector<int> &ans)
{
    // If empty tree
    if (root == nullptr)
        return;

    // If current node is of odd level
    if (isOdd)
        ans.push_back(root->data);

    // Recur for children with isOdd
    // switched.
    solve(root->left, !isOdd, ans);
    solve(root->right, !isOdd, ans);
}

vector<int> nodesAtOddLevels(Node *root)
{
    vector<int> ans;

    solve(root, true, ans);

    sort(ans.begin(), ans.end());

    return ans;
}

// Driver Code
int main()
{
    Node *root = new Node(1);

    root->left = new Node(2);
    root->right = new Node(3);

    root->left->left = new Node(4);
    root->left->right = new Node(5);

    root->right->right = new Node(6);

    root->left->right->left = new Node(7);
    root->left->right->right = new Node(8);

    root->right->right->left = new Node(9);

    vector<int> result = nodesAtOddLevels(root);

    // Printing result
    for (int x : result)
        cout << x << " ";

    return 0;
}
Java
import java.util.ArrayList;
import java.util.Collections;

class Node {
  public int data;
  public Node left;
  public Node right;

  public Node(int val) {
    data = val;
    left = null;
    right = null;
  }
}

public class GfG {
  public static void solve(Node root, boolean isOdd, ArrayList<Integer> ans) {
    // If empty tree
    if (root == null)
      return;

    // If current node is of odd level
    if (isOdd)
      ans.add(root.data);

    // Recur for children with isOdd
    // switched.
    solve(root.left,!isOdd, ans);
    solve(root.right,!isOdd, ans);
  }

  public static ArrayList<Integer> nodesAtOddLevels(Node root) {
    ArrayList<Integer> ans = new ArrayList<>();

    solve(root, true, ans);

    Collections.sort(ans);

    return ans;
  }

  // Driver Code
  public static void main(String[] args) {
    Node root = new Node(1);

    root.left = new Node(2);
    root.right = new Node(3);

    root.left.left = new Node(4);
    root.left.right = new Node(5);

    root.right.right = new Node(6);

    root.left.right.left = new Node(7);
    root.left.right.right = new Node(8);

    root.right.right.left = new Node(9);

    ArrayList<Integer> result = nodesAtOddLevels(root);

    // Printing result
    for (int x : result)
      System.out.print(x + " ");
  }
}
Python
class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None


def solve(root, isOdd, ans):
    # If empty tree
    if root is None:
        return

    # If current node is of odd level
    if isOdd:
        ans.append(root.data)

    # Recur for children with isOdd
    # switched.
    solve(root.left, not isOdd, ans)
    solve(root.right, not isOdd, ans)


def nodesAtOddLevels(root):
    ans = []

    solve(root, True, ans)

    ans.sort()

    return ans


# Driver Code
if __name__ == '__main__':
    root = Node(1)

    root.left = Node(2)
    root.right = Node(3)

    root.left.left = Node(4)
    root.left.right = Node(5)

    root.right.right = Node(6)

    root.left.right.left = Node(7)
    root.left.right.right = Node(8)

    root.right.right.left = Node(9)

    result = nodesAtOddLevels(root)

    # Printing result
    for x in result:
        print(x, end=' ')
C#
using System;
using System.Collections.Generic;
using System.Linq;

public class Node
{
  public int data;
  public Node left;
  public Node right;

  public Node(int val)
  {
    data = val;
    left = null;
    right = null;
  }
}

public class GfG
{
  public static void Solve(Node root, bool isOdd, List<int> ans)
  {
    // If empty tree
    if (root == null)
      return;

    // If current node is of odd level
    if (isOdd)
      ans.Add(root.data);

    // Recur for children with isOdd
    // switched.
    Solve(root.left,!isOdd, ans);
    Solve(root.right, !isOdd, ans);
  }

  public static List<int> NodesAtOddLevels(Node root)
  {
    List<int> ans = new List<int>();

    Solve(root, true, ans);

    ans.Sort();

    return ans;
  }

  // Driver Code
  public static void Main()
  {
    Node root = new Node(1);

    root.left = new Node(2);
    root.right = new Node(3);

    root.left.left = new Node(4);
    root.left.right = new Node(5);

    root.right.right = new Node(6);

    root.left.right.left = new Node(7);
    root.left.right.right = new Node(8);

    root.right.right.left = new Node(9);

    List<int> result = NodesAtOddLevels(root);

    // Printing result
    foreach (int x in result)
      Console.Write(x + " ");
  }
}
JavaScript
class Node {
  constructor(val) {
    this.data = val;
    this.left = null;
    this.right = null;
  }
}

function solve(root, isOdd, ans) {
  // If empty tree
  if (root === null)
    return;

  // If current node is of odd level
  if (isOdd)
    ans.push(root.data);

  // Recur for children with isOdd
  // switched.
  solve(root.left, !isOdd, ans);
  solve(root.right,!isOdd, ans);
}

function nodesAtOddLevels(root) {
  let ans = [];

  solve(root, true, ans);

  ans.sort((a, b) => a - b);

  return ans;
}

// Driver Code
let root = new Node(1);

root.left = new Node(2);
root.right = new Node(3);

root.left.left = new Node(4);
root.left.right = new Node(5);

root.right.right = new Node(6);

root.left.right.left = new Node(7);
root.left.right.right = new Node(8);

root.right.right.left = new Node(9);

let result = nodesAtOddLevels(root);

// Printing result
console.log(result.join(' '));

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.
C++
#include <bits/stdc++.h>
using namespace std;

class Node
{
  public:
    int data;
    Node *left;
    Node *right;

    Node(int val)
    {
        data = val;
        left = nullptr;
        right = nullptr;
    }
};

vector<int> nodesAtOddLevels(Node *root)
{
    vector<int> ans;

    // Base Case
    if (root == nullptr)
        return ans;

    // Create an empty queue for level
    // order traversal
    queue<Node *> q;

    // Enqueue root and initialize level as odd
    q.push(root);
    bool isOdd = true;

    while (1)
    {
        // nodeCount (queue size) indicates
        // number of nodes at current level.
        int nodeCount = q.size();
        if (nodeCount == 0)
            break;

        // Dequeue all nodes of current level
        // and Enqueue all nodes of next level
        while (nodeCount > 0)
        {
            Node *node = q.front();
            if (isOdd)
                ans.push_back(node->data);
            q.pop();
            if (node->left != nullptr)
                q.push(node->left);
            if (node->right != nullptr)
                q.push(node->right);
            nodeCount--;
        }

        isOdd = !isOdd;
    }

    sort(ans.begin(), ans.end());

    return ans;
}

// Driver Code
int main()
{
    // Creating the tree using constructor
    Node *root = new Node(1);

    root->left = new Node(2);
    root->right = new Node(3);

    root->left->left = new Node(4);
    root->left->right = new Node(5);

    root->right->right = new Node(6);

    root->left->right->left = new Node(7);
    root->left->right->right = new Node(8);

    root->right->right->left = new Node(9);

    vector<int> result = nodesAtOddLevels(root);

    for (int x : result)
        cout << x << " ";

    return 0;
}
Java
import java.util.LinkedList;
import java.util.Queue;
import java.util.ArrayList;

class Node {
  public int data;
  public Node left;
  public Node right;

  public Node(int val) {
    data = val;
    left = null;
    right = null;
  }
}

public class GfG {
  public static ArrayList<Integer> nodesAtOddLevels(Node root) {
    ArrayList<Integer> ans = new ArrayList<>();

    // Base Case
    if (root == null)
      return ans;

    // Create an empty queue for level
    // order traversal
    Queue<Node> q = new LinkedList<>();

    // Enqueue root and initialize level as odd
    q.add(root);
    boolean isOdd = true;

    while (true) {
      // nodeCount (queue size) indicates
      // number of nodes at current level.
      int nodeCount = q.size();
      if (nodeCount == 0)
        break;

      // Dequeue all nodes of current level
      // and Enqueue all nodes of next level
      while (nodeCount > 0) {
        Node node = q.poll();
        if (isOdd)
          ans.add(node.data);
        if (node.left!= null)
          q.add(node.left);
        if (node.right!= null)
          q.add(node.right);
        nodeCount--;
      }

      isOdd = !isOdd;
    }

    ans.sort(null);

    return ans;
  }

  public static void main(String[] args) {
    // Creating the tree using constructor
    Node root = new Node(1);

    root.left = new Node(2);
    root.right = new Node(3);

    root.left.left = new Node(4);
    root.left.right = new Node(5);

    root.right.right = new Node(6);

    root.left.right.left = new Node(7);
    root.left.right.right = new Node(8);

    root.right.right.left = new Node(9);

    ArrayList<Integer> result = nodesAtOddLevels(root);
    for (int x : result)
      System.out.print(x + " ");
  }
}
Python
from collections import deque

class Node:
  def __init__(self, val):
    self.data = val
    self.left = None
    self.right = None

def nodesAtOddLevels(root):
  ans = []

  # Base Case
  if root is None:
    return ans

  # Create an empty queue for level
  # order traversal
  q = deque()

  # Enqueue root and initialize level as odd
  q.append(root)
  isOdd = True

  while True:
    # nodeCount (queue size) indicates
    # number of nodes at current level.
    nodeCount = len(q)
    if nodeCount == 0:
      break

    # Dequeue all nodes of current level
    # and Enqueue all nodes of next level
    while nodeCount > 0:
      node = q.popleft()
      if isOdd:
        ans.append(node.data)
      if node.left is not None:
        q.append(node.left)
      if node.right is not None:
        q.append(node.right)
      nodeCount -= 1

    isOdd = not isOdd

  ans.sort()

  return ans

# Driver Code
if __name__ == '__main__':
    
  # Creating the tree using constructor
  root = Node(1)

  root.left = Node(2)
  root.right = Node(3)

  root.left.left = Node(4)
  root.left.right = Node(5)

  root.right.right = Node(6)

  root.left.right.left = Node(7)
  root.left.right.right = Node(8)

  root.right.right.left = Node(9)

  result = nodesAtOddLevels(root)
  for x in result:
    print(x, end=' ')
C#
using System;
using System.Collections.Generic;
using System.Linq;

class Node
{
  public int data;
  public Node left;
  public Node right;

  public Node(int val)
  {
    data = val;
    left = null;
    right = null;
  }
}

class GfG
{
  static List<int> nodesAtOddLevels(Node root)
  {
    List<int> ans = new List<int>();

    // Base Case
    if (root == null)
      return ans;

    // Create an empty queue for level
    // order traversal
    Queue<Node> q = new Queue<Node>();

    // Enqueue root and initialize level as odd
    q.Enqueue(root);
    bool isOdd = true;

    while (true)
    {
      // nodeCount (queue size) indicates
      // number of nodes at current level.
      int nodeCount = q.Count;
      if (nodeCount == 0)
        break;

      // Dequeue all nodes of current level
      // and Enqueue all nodes of next level
      while (nodeCount > 0)
      {
        Node node = q.Dequeue();
        if (isOdd)
          ans.Add(node.data);
        if (node.left!= null)
          q.Enqueue(node.left);
        if (node.right!= null)
          q.Enqueue(node.right);
        nodeCount--;
      }

      isOdd = !isOdd;
    }

    ans.Sort();

    return ans;
  }

  static void Main(string[] args)
  {
    // Creating the tree using constructor
    Node root = new Node(1);

    root.left = new Node(2);
    root.right = new Node(3);

    root.left.left = new Node(4);
    root.left.right = new Node(5);

    root.right.right = new Node(6);

    root.left.right.left = new Node(7);
    root.left.right.right = new Node(8);

    root.right.right.left = new Node(9);

    List<int> result = nodesAtOddLevels(root);
    foreach (int x in result)
      Console.Write(x + " ");
  }
}
JavaScript
class Node {
  constructor(val) {
    this.data = val;
    this.left = null;
    this.right = null;
  }
}

function nodesAtOddLevels(root) {
  let ans = [];

  // Base Case
  if (root === null)
    return ans;

  // Create an empty queue for level
  // order traversal
  let q = [];

  // Enqueue root and initialize level as odd
  q.push(root);
  let isOdd = true;

  while (true) {
    // nodeCount (queue size) indicates
    // number of nodes at current level.
    let nodeCount = q.length;
    if (nodeCount === 0)
      break;

    // Dequeue all nodes of current level
    // and Enqueue all nodes of next level
    while (nodeCount > 0) {
      let node = q.shift();
      if (isOdd)
        ans.push(node.data);
      if (node.left!== null)
        q.push(node.left);
      if (node.right!== null)
        q.push(node.right);
      nodeCount--;
    }

    isOdd = !isOdd;
  }

  ans.sort((a, b) => a - b);

  return ans;
}

// Driver Code
// Creating the tree using constructor
let root = new Node(1);

root.left = new Node(2);
root.right = new Node(3);

root.left.left = new Node(4);
root.left.right = new Node(5);

root.right.right = new Node(6);

root.left.right.left = new Node(7);
root.left.right.right = new Node(8);

root.right.right.left = new Node(9);

let result = nodesAtOddLevels(root);
console.log(result.join(' '));

Output
1 4 5 6 

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

Comment