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>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=nullptr;right=nullptr;}};voidsolve(Node*root,boolisOdd,vector<int>&ans){// If empty treeif(root==nullptr)return;// If current node is of odd levelif(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());returnans;}// Driver Codeintmain(){Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->right=newNode(6);root->left->right->left=newNode(7);root->left->right->right=newNode(8);root->right->right->left=newNode(9);vector<int>result=nodesAtOddLevels(root);// Printing resultfor(intx:result)cout<<x<<" ";return0;}
Java
importjava.util.ArrayList;importjava.util.Collections;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=null;right=null;}}publicclassGfG{publicstaticvoidsolve(Noderoot,booleanisOdd,ArrayList<Integer>ans){// If empty treeif(root==null)return;// If current node is of odd levelif(isOdd)ans.add(root.data);// Recur for children with isOdd// switched.solve(root.left,!isOdd,ans);solve(root.right,!isOdd,ans);}publicstaticArrayList<Integer>nodesAtOddLevels(Noderoot){ArrayList<Integer>ans=newArrayList<>();solve(root,true,ans);Collections.sort(ans);returnans;}// Driver Codepublicstaticvoidmain(String[]args){Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.right=newNode(6);root.left.right.left=newNode(7);root.left.right.right=newNode(8);root.right.right.left=newNode(9);ArrayList<Integer>result=nodesAtOddLevels(root);// Printing resultfor(intx:result)System.out.print(x+" ");}}
Python
classNode:def__init__(self,val):self.data=valself.left=Noneself.right=Nonedefsolve(root,isOdd,ans):# If empty treeifrootisNone:return# If current node is of odd levelifisOdd:ans.append(root.data)# Recur for children with isOdd# switched.solve(root.left,notisOdd,ans)solve(root.right,notisOdd,ans)defnodesAtOddLevels(root):ans=[]solve(root,True,ans)ans.sort()returnans# Driver Codeif__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 resultforxinresult:print(x,end=' ')
C#
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;publicclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=null;right=null;}}publicclassGfG{publicstaticvoidSolve(Noderoot,boolisOdd,List<int>ans){// If empty treeif(root==null)return;// If current node is of odd levelif(isOdd)ans.Add(root.data);// Recur for children with isOdd// switched.Solve(root.left,!isOdd,ans);Solve(root.right,!isOdd,ans);}publicstaticList<int>NodesAtOddLevels(Noderoot){List<int>ans=newList<int>();Solve(root,true,ans);ans.Sort();returnans;}// Driver CodepublicstaticvoidMain(){Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.right=newNode(6);root.left.right.left=newNode(7);root.left.right.right=newNode(8);root.right.right.left=newNode(9);List<int>result=NodesAtOddLevels(root);// Printing resultforeach(intxinresult)Console.Write(x+" ");}}
JavaScript
classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}functionsolve(root,isOdd,ans){// If empty treeif(root===null)return;// If current node is of odd levelif(isOdd)ans.push(root.data);// Recur for children with isOdd// switched.solve(root.left,!isOdd,ans);solve(root.right,!isOdd,ans);}functionnodesAtOddLevels(root){letans=[];solve(root,true,ans);ans.sort((a,b)=>a-b);returnans;}// Driver Codeletroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.right=newNode(6);root.left.right.left=newNode(7);root.left.right.right=newNode(8);root.right.right.left=newNode(9);letresult=nodesAtOddLevels(root);// Printing resultconsole.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>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=nullptr;right=nullptr;}};vector<int>nodesAtOddLevels(Node*root){vector<int>ans;// Base Caseif(root==nullptr)returnans;// Create an empty queue for level// order traversalqueue<Node*>q;// Enqueue root and initialize level as oddq.push(root);boolisOdd=true;while(1){// nodeCount (queue size) indicates// number of nodes at current level.intnodeCount=q.size();if(nodeCount==0)break;// Dequeue all nodes of current level// and Enqueue all nodes of next levelwhile(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());returnans;}// Driver Codeintmain(){// Creating the tree using constructorNode*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->right=newNode(6);root->left->right->left=newNode(7);root->left->right->right=newNode(8);root->right->right->left=newNode(9);vector<int>result=nodesAtOddLevels(root);for(intx:result)cout<<x<<" ";return0;}
Java
importjava.util.LinkedList;importjava.util.Queue;importjava.util.ArrayList;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=null;right=null;}}publicclassGfG{publicstaticArrayList<Integer>nodesAtOddLevels(Noderoot){ArrayList<Integer>ans=newArrayList<>();// Base Caseif(root==null)returnans;// Create an empty queue for level// order traversalQueue<Node>q=newLinkedList<>();// Enqueue root and initialize level as oddq.add(root);booleanisOdd=true;while(true){// nodeCount (queue size) indicates// number of nodes at current level.intnodeCount=q.size();if(nodeCount==0)break;// Dequeue all nodes of current level// and Enqueue all nodes of next levelwhile(nodeCount>0){Nodenode=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);returnans;}publicstaticvoidmain(String[]args){// Creating the tree using constructorNoderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.right=newNode(6);root.left.right.left=newNode(7);root.left.right.right=newNode(8);root.right.right.left=newNode(9);ArrayList<Integer>result=nodesAtOddLevels(root);for(intx:result)System.out.print(x+" ");}}
Python
fromcollectionsimportdequeclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=NonedefnodesAtOddLevels(root):ans=[]# Base CaseifrootisNone:returnans# Create an empty queue for level# order traversalq=deque()# Enqueue root and initialize level as oddq.append(root)isOdd=TruewhileTrue:# nodeCount (queue size) indicates# number of nodes at current level.nodeCount=len(q)ifnodeCount==0:break# Dequeue all nodes of current level# and Enqueue all nodes of next levelwhilenodeCount>0:node=q.popleft()ifisOdd:ans.append(node.data)ifnode.leftisnotNone:q.append(node.left)ifnode.rightisnotNone:q.append(node.right)nodeCount-=1isOdd=notisOddans.sort()returnans# Driver Codeif__name__=='__main__':# Creating the tree using constructorroot=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)forxinresult:print(x,end=' ')
C#
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=null;right=null;}}classGfG{staticList<int>nodesAtOddLevels(Noderoot){List<int>ans=newList<int>();// Base Caseif(root==null)returnans;// Create an empty queue for level// order traversalQueue<Node>q=newQueue<Node>();// Enqueue root and initialize level as oddq.Enqueue(root);boolisOdd=true;while(true){// nodeCount (queue size) indicates// number of nodes at current level.intnodeCount=q.Count;if(nodeCount==0)break;// Dequeue all nodes of current level// and Enqueue all nodes of next levelwhile(nodeCount>0){Nodenode=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();returnans;}staticvoidMain(string[]args){// Creating the tree using constructorNoderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.right=newNode(6);root.left.right.left=newNode(7);root.left.right.right=newNode(8);root.right.right.left=newNode(9);List<int>result=nodesAtOddLevels(root);foreach(intxinresult)Console.Write(x+" ");}}
JavaScript
classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}functionnodesAtOddLevels(root){letans=[];// Base Caseif(root===null)returnans;// Create an empty queue for level// order traversalletq=[];// Enqueue root and initialize level as oddq.push(root);letisOdd=true;while(true){// nodeCount (queue size) indicates// number of nodes at current level.letnodeCount=q.length;if(nodeCount===0)break;// Dequeue all nodes of current level// and Enqueue all nodes of next levelwhile(nodeCount>0){letnode=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);returnans;}// Driver Code// Creating the tree using constructorletroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.right=newNode(6);root.left.right.left=newNode(7);root.left.right.right=newNode(8);root.right.right.left=newNode(9);letresult=nodesAtOddLevels(root);console.log(result.join(' '));
Output
1 4 5 6
Time complexity: O(n log n)Â Auxiliary Space: O(n)