Print the nodes at odd levels of a tree

Given a binary tree, print nodes of odd level in any order. Root is considered at level 1.

For example consider the following tree
          1
       /     \
      2       3
    /   \       \
   4     5       6
        /  \     /
       7    8   9

Output  1 4 5 6

Method 1 (Recursive)



The idea is to pass initial level as odd and switch level flag in every recursive call. For every node, if odd flag is set, then print it.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// Recursive C++ program to print odd level nodes
#include <bits/stdc++.h>
using namespace std;
  
struct Node {
    int data;
    Node* left, *right;
};
  
void printOddNodes(Node *root, bool isOdd = true)
{
    // If empty tree
    if (root == NULL)
      return;
  
    // If current node is of odd level
    if (isOdd)
       cout << root->data << " " ;
  
    // Recur for children with isOdd
    // switched.
    printOddNodes(root->left, !isOdd);
    printOddNodes(root->right, !isOdd);
}
  
// Utility method to create a node
struct Node* newNode(int data)
{
    struct Node* node = new Node;
    node->data = data;
    node->left = node->right = NULL;
    return (node);
}
  
// Driver code
int main()
{
    struct Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    printOddNodes(root);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Recursive Java program to print odd level nodes 
class GfG {
  
static class Node { 
    int data; 
    Node left, right; 
}
  
static void printOddNodes(Node root, boolean isOdd) 
    // If empty tree 
    if (root == null
    return
  
    // If current node is of odd level 
    if (isOdd == true
    System.out.print(root.data + " "); 
  
    // Recur for children with isOdd 
    // switched. 
    printOddNodes(root.left, !isOdd); 
    printOddNodes(root.right, !isOdd); 
  
// Utility method to create a node 
static Node newNode(int data) 
    Node node = new Node(); 
    node.data = data; 
    node.left = null;
    node.right = null
    return (node); 
  
// Driver code 
public static void main(String[] args) 
    Node root = newNode(1); 
    root.left = newNode(2); 
    root.right = newNode(3); 
    root.left.left = newNode(4); 
    root.left.right = newNode(5); 
    printOddNodes(root, true); 
  
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Recursive Python3 program to print 
# odd level nodes 
  
# Utility method to create a node 
class newNode:
    def __init__(self, data):
        self.data = data 
        self.left = self.right = None
  
def printOddNodes(root, isOdd = True):
      
    # If empty tree 
    if (root == None): 
        return
  
    # If current node is of odd level 
    if (isOdd): 
        print(root.data, end = " ")
  
    # Recur for children with isOdd 
    # switched. 
    printOddNodes(root.left, not isOdd) 
    printOddNodes(root.right, not isOdd)
  
# Driver code 
if __name__ == '__main__':
    root = newNode(1
    root.left = newNode(2
    root.right = newNode(3
    root.left.left = newNode(4
    root.left.right = newNode(5
    printOddNodes(root)
      
# This code is contributed by PranchalK

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

using System;
  
// Recursive C# program to print odd level nodes  
public class GfG
{
  
public class Node
{
    public int data;
    public Node left, right;
}
  
public static void printOddNodes(Node root, bool isOdd)
{
    // If empty tree  
    if (root == null)
    {
    return;
    }
  
    // If current node is of odd level  
    if (isOdd == true)
    {
    Console.Write(root.data + " ");
    }
  
    // Recur for children with isOdd  
    // switched.  
    printOddNodes(root.left, !isOdd);
    printOddNodes(root.right, !isOdd);
}
  
// Utility method to create a node  
public static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = null;
    node.right = null;
    return (node);
}
  
// Driver code  
public static void Main(string[] args)
{
    Node root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(3);
    root.left.left = newNode(4);
    root.left.right = newNode(5);
    printOddNodes(root, true);
  
}
}
  
// This code is contributed by Shrikant13

chevron_right



Output:

1 4 5

Time complexity : O(n)

Method 2 (Iterative)

The above code prints nodes in preorder way. If we wish to print nodes level by level, we can use level order traversal. The idea is based on Print level order traversal line by line

We traverse nodes level by level. We switch odd level flag after every level.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// Iterative C++ program to print odd level nodes
#include <bits/stdc++.h>
using namespace std;
  
struct Node {
    int data;
    Node* left, *right;
};
  
// Iterative method to do level order traversal line by line
void printOddNodes(Node *root)
{
    // Base Case
    if (root == NULL)  return;
  
    // Create an empty queue for level
    // order tarversal
    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)
               cout << node->data << " ";
            q.pop();
            if (node->left != NULL)
                q.push(node->left);
            if (node->right != NULL)
                q.push(node->right);
            nodeCount--;
        }
  
        isOdd = !isOdd;
    }
}
  
// Utility method to create a node
struct Node* newNode(int data)
{
    struct Node* node = new Node;
    node->data = data;
    node->left = node->right = NULL;
    return (node);
}
  
// Driver code
int main()
{
    struct Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    printOddNodes(root);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Iterative Java program to print odd level nodes 
import java.util.*;
class GfG {
  
static class Node { 
    int data; 
    Node left, right; 
}
  
// Iterative method to do level order traversal line by line 
static void printOddNodes(Node root) 
    // Base Case 
    if (root == null) return
  
    // Create an empty queue for level 
    // order tarversal 
    Queue<Node> q = new LinkedList<Node> (); 
  
    // 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.peek(); 
            if (isOdd == true
            System.out.print(node.data + " "); 
            q.remove(); 
            if (node.left != null
                q.add(node.left); 
            if (node.right != null
                q.add(node.right); 
            nodeCount--; 
        
  
        isOdd = !isOdd; 
    
  
// Utility method to create a node 
static Node newNode(int data) 
    Node node = new Node(); 
    node.data = data; 
    node.left = null;
    node.right = null
    return (node); 
  
// Driver code 
public static void main(String[] args) 
    Node root = newNode(1); 
    root.left = newNode(2); 
    root.right = newNode(3); 
    root.left.left = newNode(4); 
    root.left.right = newNode(5); 
    printOddNodes(root); 

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Iterative Python3 program to prodd
# level nodes
  
# A Binary Tree Node
# Utility function to create a
# new tree Node 
class newNode: 
    def __init__(self, data): 
        self.data = data 
        self.left = self.right = None
          
# Iterative method to do level order
# traversal line by line 
def printOddNodes(root) :
  
    # Base Case 
    if (root == None):
        return
  
    # Create an empty queue for  
    # level order tarversal 
    q = []
  
    # Enqueue root and initialize
    # level as odd 
    q.append(root) 
    isOdd = True
  
    while (1) :
      
        # 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[0]
            if (isOdd): 
                print(node.data, end = " ")
            q.pop(0
            if (node.left != None) :
                q.append(node.left) 
            if (node.right != None) :
                q.append(node.right) 
            nodeCount -= 1
              
        isOdd = not isOdd 
  
# Driver Code 
if __name__ == '__main__':
    root = newNode(1
    root.left = newNode(2
    root.right = newNode(3
    root.left.left = newNode(4
    root.left.right = newNode(5
    printOddNodes(root)
  
# This code is contributed
# by SHUBHAMSINGH10

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// Iterative C# program to 
// print odd level nodes
using System;
using System.Collections.Generic;
  
public class GfG 
{
    public class Node 
    
        public int data; 
        public Node left, right; 
    }
  
    // Iterative method to do level 
    // order traversal line by line 
    static void printOddNodes(Node root) 
    
        // Base Case 
        if (root == null) return
  
        // Create an empty queue for level 
        // order tarversal 
        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.Peek(); 
                if (isOdd == true
                    Console.Write(node.data + " "); 
                q.Dequeue(); 
                if (node.left != null
                    q.Enqueue(node.left); 
                if (node.right != null
                    q.Enqueue(node.right); 
                nodeCount--; 
            
            isOdd = !isOdd; 
        
    
  
    // Utility method to create a node 
    static Node newNode(int data) 
    
        Node node = new Node(); 
        node.data = data; 
        node.left = null;
        node.right = null
        return (node); 
    
  
    // Driver code 
    public static void Main(String[] args) 
    
        Node root = newNode(1); 
        root.left = newNode(2); 
        root.right = newNode(3); 
        root.left.left = newNode(4); 
        root.left.right = newNode(5); 
        printOddNodes(root); 
    
}
  
// This code has been contributed
// by 29AjayKumar

chevron_right



Output:

1 4 5

Time complexity : O(n)

This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up



Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.