Print the nodes at odd levels of a tree - GeeksforGeeks

16 Mar, 2022
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++
Java
Python3
C#
Javascript
// 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 nodestruct Node* newNode(int data){    struct Node* node = new Node;    node->data = data;    node->left = node->right = NULL;    return (node);} // Driver codeint 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;}
// Recursive Java program to print odd level nodesclass 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 nodestatic Node newNode(int data){    Node node = new Node();    node.data = data;    node.left = null;    node.right = null;    return (node);} // Driver codepublic 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); }}
# Recursive Python3 program to print# odd level nodes # Utility method to create a nodeclass 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 codeif __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
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
<script>     // Recursive JavaScript program to print odd level nodes         class Node    {        constructor(data) {           this.left = null;           this.right = null;           this.data = data;        }    }         function printOddNodes(root, isOdd)    {        // If empty tree        if (root == null)        return;         // If current node is of odd level        if (isOdd == true)        document.write(root.data + " ");         // Recur for children with isOdd        // switched.        printOddNodes(root.left, !isOdd);        printOddNodes(root.right, !isOdd);    }     // Utility method to create a node    function newNode(data)    {        let node = new Node(data);        return (node);    }         let root = newNode(1);    root.left = newNode(2);    root.right = newNode(3);    root.left.left = newNode(4);    root.left.right = newNode(5);    printOddNodes(root, true);     </script>
Output:  
1 4 5
Time complexity : O(n)Auxiliary Space: O(n) for Recursive Stack Space in case of Skewed Tree
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 lineWe traverse nodes level by level. We switch odd level flag after every level.  
C++
Java
Python3
C#
Javascript
// 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 linevoid printOddNodes(Node *root){    // Base Case    if (root == NULL)  return;     // 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)               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 nodestruct Node* newNode(int data){    struct Node* node = new Node;    node->data = data;    node->left = node->right = NULL;    return (node);} // Driver codeint 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;}
// Iterative Java program to print odd level nodesimport java.util.*;class GfG { static class Node {    int data;    Node left, right;} // Iterative method to do level order traversal line by linestatic void printOddNodes(Node root){    // Base Case    if (root == null) return;     // Create an empty queue for level    // order traversal    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 nodestatic Node newNode(int data){    Node node = new Node();    node.data = data;    node.left = null;    node.right = null;    return (node);} // Driver codepublic 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);}}
# Iterative Python3 program to print odd# level nodes # A Binary Tree Node# Utility function to create a# new tree Nodeclass newNode:    def __init__(self, data):        self.data = data        self.left = self.right = None         # Iterative method to do level order# traversal line by linedef printOddNodes(root) :     # Base Case    if (root == None):        return     # Create an empty queue for     # level order traversal    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 Codeif __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
// Iterative C# program to// print odd level nodesusing 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 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.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
<script>// Iterative Javascript program to print odd level nodes class Node{    constructor(data)    {        this.data=data;        this.left=this.right=null;    }} function printOddNodes(root){    // Base Case    if (root == null) return;      // 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[0];            if (isOdd == true)                document.write(node.data + " ");            q.shift();            if (node.left != null)                q.push(node.left);            if (node.right != null)                q.push(node.right);            nodeCount--;        }          isOdd = !isOdd;    }} // Driver codelet 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);printOddNodes(root); // This code is contributed by rag2127</script>
Output:  
1 4 5
Time complexity : O(n) Auxiliary Space: O(n) for Queue Data Structure 
YouTubeGeeksforGeeks507K subscribersPrint the nodes at odd levels of a tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:21•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=38Sm_29KJ3E" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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. 
prerna saini
shrikanth13
PranchalKatiyar
SHUBHAMSINGH10
29AjayKumar
anikakapoor
rameshtravel07
rag2127
prasanna1995
simmytarika5
Accolite
tree-level-order
Tree
Accolite
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
AVL Tree | Set 1 (Insertion)
Level Order Binary Tree Traversal
Binary Tree | Set 3 (Types of Binary Tree)
Inorder Tree Traversal without Recursion
Write a Program to Find the Maximum Depth or Height of a Tree
Binary Tree | Set 2 (Properties)
Decision Tree
A program to check if a binary tree is BST or not