Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Print odd positioned nodes of odd levels in level order of the given binary tree
Next article icon

Print odd positioned nodes of even levels in level order of the given binary tree

Last Updated : 23 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a binary tree, the task is to print the odd positioned nodes of even levels in the level order traversal of the tree. The root is considered at level 0, and the leftmost node of any level is considered as a node at position 0.
Example: 
 

Input:            1          /    \         2       3       / \      /  \      4   5    6    7         /  \             8    9       /      \      10       11 Output: 5 7 11  Input:       2     /   \    4     15   /     /  45   17 Output: 17

 

Prerequisite – Even positioned elements at even level 
Approach: To print nodes level by level, use level order traversal. The idea is based on Print level order traversal line by line. For that, traverse nodes level by level and switch odd level flag after every level. Similarly, mark 2nd node in every level as odd position and switch it after each time the next node is processed.
Below is the implementation of the above approach:
 

C++




// C++ implementation of the approach
#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 printEvenLevelOddNodes(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 even
    q.push(root);
    bool evenLevel = true;
 
    while (1) {
 
        // nodeCount (queue size) indicates
        // number of nodes in the current level
        int nodeCount = q.size();
        if (nodeCount == 0)
            break;
 
        // Mark 1st node as even positioned
        bool evenNodePosition = true;
 
        // Dequeue all the nodes of current level
        // and Enqueue all the nodes of next level
        while (nodeCount > 0) {
            Node* node = q.front();
 
            // Print only even positioned
            // nodes of even levels
            if (evenLevel && !evenNodePosition)
                cout << node->data << " ";
            q.pop();
            if (node->left != NULL)
                q.push(node->left);
            if (node->right != NULL)
                q.push(node->right);
            nodeCount--;
 
            // Switch the even position flag
            evenNodePosition = !evenNodePosition;
        }
 
        // Switch the even level flag
        evenLevel = !evenLevel;
    }
}
 
// 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);
    root->right->left = newNode(6);
    root->right->right = newNode(7);
    root->left->right->left = newNode(8);
    root->left->right->right = newNode(9);
    root->left->right->left->left = newNode(10);
    root->left->right->right->right = newNode(11);
 
    printEvenLevelOddNodes(root);
 
    return 0;
}
 
 

Java




// Java implementation of the above approach
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 printEvenLevelOddNodes(Node root)
{
    // Base Case
    if (root == null)
        return;
 
    // Create an empty queue for level
    // order traversal
    Queue<Node> q = new LinkedList<>();
 
    // Enqueue root and initialize level as even
    q.add(root);
    boolean evenLevel = true;
 
    while (true)
    {
 
        // nodeCount (queue size) indicates
        // number of nodes in the current level
        int nodeCount = q.size();
        if (nodeCount == 0)
            break;
 
        // Mark 1st node as even positioned
        boolean evenNodePosition = true;
 
        // Dequeue all the nodes of current level
        // and Enqueue all the nodes of next level
        while (nodeCount > 0)
        {
            Node node = q.peek();
 
            // Print only even positioned
            // nodes of even levels
            if (evenLevel && !evenNodePosition)
                System.out.print(node.data + " ");
 
            q.remove();
            if (node.left != null)
                q.add(node.left);
            if (node.right != null)
                q.add(node.right);
            nodeCount--;
 
            // Switch the even position flag
            evenNodePosition = !evenNodePosition;
        }
 
        // Switch the even level flag
        evenLevel = !evenLevel;
    }
}
 
// Utility method to create a node
static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = 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);
    root.right.left = newNode(6);
    root.right.right = newNode(7);
    root.left.right.left = newNode(8);
    root.left.right.right = newNode(9);
    root.left.right.left.left = newNode(10);
    root.left.right.right.right = newNode(11);
 
    printEvenLevelOddNodes(root);
}
}
 
// This code is contributed by Princi Singh
 
 

Python3




# Python implementation of the approach
 
# Utility method to create a node
class newNode:
 
    # Construct to create a new node
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None
 
# Iterative method to do level order
# traversal line by line
def printEvenLevelOddNodes(root):
    # Base Case
    if (root == None):
        return
     
    # Create an empty queue for level
    # order traversal
    q =[]
     
    # Enqueue root and initialize level as even
    q.append(root)
    evenLevel = True
     
    while (1):
         
        # nodeCount (queue size) indicates
        # number of nodes in the current level
        nodeCount = len(q)
        if (nodeCount == 0):
            break
         
        # Mark 1st node as even positioned
        evenNodePosition = True
         
        # Dequeue all the nodes of current level
        # and Enqueue all the nodes of next level
        while (nodeCount > 0):
            node = q[0]
            # Pronly even positioned
            # nodes of even levels
            if evenLevel and not evenNodePosition:
                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
             
            # Switch the even position flag
            evenNodePosition = not evenNodePosition
         
        # Switch the even level flag
        evenLevel = not evenLevel
     
 
 
# 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)
    root.right.left = newNode(6)
    root.right.right = newNode(7)
    root.left.right.left = newNode(8)
    root.left.right.right = newNode(9)
    root.left.right.left.left = newNode(10)
    root.left.right.right.right = newNode(11)
 
    printEvenLevelOddNodes(root)
 
 

C#




// C# implementation of the above approach
using System;
using System.Collections.Generic;
     
class GFG
{
public class Node
{
    public int data;
    public Node left, right;
};
 
// Iterative method to do level order
// traversal line by line
static void printEvenLevelOddNodes(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 even
    q.Enqueue(root);
    bool evenLevel = true;
 
    while (true)
    {
 
        // nodeCount (queue size) indicates
        // number of nodes in the current level
        int nodeCount = q.Count;
        if (nodeCount == 0)
            break;
 
        // Mark 1st node as even positioned
        bool evenNodePosition = true;
 
        // Dequeue all the nodes of current level
        // and Enqueue all the nodes of next level
        while (nodeCount > 0)
        {
            Node node = q.Peek();
 
            // Print only even positioned
            // nodes of even levels
            if (evenLevel && !evenNodePosition)
                Console.Write(node.data + " ");
 
            q.Dequeue();
            if (node.left != null)
                q.Enqueue(node.left);
            if (node.right != null)
                q.Enqueue(node.right);
            nodeCount--;
 
            // Switch the even position flag
            evenNodePosition = !evenNodePosition;
        }
 
        // Switch the even level flag
        evenLevel = !evenLevel;
    }
}
 
// Utility method to create a node
static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = 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);
    root.right.left = newNode(6);
    root.right.right = newNode(7);
    root.left.right.left = newNode(8);
    root.left.right.right = newNode(9);
    root.left.right.left.left = newNode(10);
    root.left.right.right.right = newNode(11);
 
    printEvenLevelOddNodes(root);
}
}
 
// This code is contributed by 29AjayKumar
 
 

Javascript




<script>
 
    // JavaScript implementation of the above approach
     
    class Node
    {
        constructor(data) {
           this.left = null;
           this.right = null;
           this.data = data;
        }
    }
 
    // Iterative method to do level order
    // traversal line by line
    function printEvenLevelOddNodes(root)
    {
        // Base Case
        if (root == null)
            return;
 
        // Create an empty queue for level
        // order traversal
        let q = [];
 
        // Enqueue root and initialize level as even
        q.push(root);
        let evenLevel = true;
 
        while (true)
        {
 
            // nodeCount (queue size) indicates
            // number of nodes in the current level
            let nodeCount = q.length;
            if (nodeCount == 0)
                break;
 
            // Mark 1st node as even positioned
            let evenNodePosition = true;
 
            // Dequeue all the nodes of current level
            // and Enqueue all the nodes of next level
            while (nodeCount > 0)
            {
                let node = q[0];
 
                // Print only even positioned
                // nodes of even levels
                if (evenLevel && !evenNodePosition)
                    document.write(node.data + " ");
 
                q.shift();
                if (node.left != null)
                    q.push(node.left);
                if (node.right != null)
                    q.push(node.right);
                nodeCount--;
 
                // Switch the even position flag
                evenNodePosition = !evenNodePosition;
            }
 
            // Switch the even level flag
            evenLevel = !evenLevel;
        }
    }
 
    // 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);
    root.right.left = newNode(6);
    root.right.right = newNode(7);
    root.left.right.left = newNode(8);
    root.left.right.right = newNode(9);
    root.left.right.left.left = newNode(10);
    root.left.right.right.right = newNode(11);
   
    printEvenLevelOddNodes(root);
 
</script>
 
 
Output: 
5 7 11

 

Time Complexity: O(n) where n is the number of nodes in the binary tree.
Auxiliary Space: O(n) where n is the number of nodes in the binary tree.



Next Article
Print odd positioned nodes of odd levels in level order of the given binary tree

S

SHUBHAMSINGH10
Improve
Article Tags :
  • DSA
  • Mathematical
  • Queue
  • Tree
Practice Tags :
  • Mathematical
  • Queue
  • Tree

Similar Reads

  • Print even positioned nodes of odd levels in level order of the given binary tree
    Given a binary tree, the task is to print the even positioned nodes of odd levels in the level order traversal of the tree. The root is considered at level 0, and the leftmost node of any level is considered as a node at position 0.Example: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 / \ 10 11 Output:
    8 min read
  • Print odd positioned nodes of odd levels in level order of the given binary tree
    Given a binary tree, the task is to print the odd positioned nodes of odd levels in the level order traversal of the tree. The root is considered at level 0, and the leftmost node of any level is considered as a node at position 0.Example: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 / \ 10 11 Output: 3
    8 min read
  • Print even positioned nodes of even levels in level order of the given binary tree
    Given a binary tree, print even positioned nodes of even level in level order traversal. The root is considered at level 0, and the left most node of any level is considered as a node at position 0. Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 / \ 7 8 / \ 9 10 Output: 1 4 6 9 Input: 2 / \ 4 15 / / 45 17 O
    8 min read
  • Reverse the order of all nodes at even position in given Linked List
    Given a linked list A[] of N integers, the task is to reverse the order of all integers at an even position. Examples: Input: A[] = 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULLOutput: 1 6 3 4 5 2Explanation: Nodes at even position in the given linked list are 2, 4 and 6. So, after reversing
    10 min read
  • Print all the nodes except the leftmost node in every level of the given binary tree
    Given a binary tree, the task is to print all the nodes except the leftmost in every level of the tree. The root is considered at level 0, and left most node of any level is considered as a node at position 0. Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 / \ 7 8 / \ 9 10 Output: 3 5 6 8 10 Input: 1 / \ 2
    8 min read
  • Find Level wise positions of given node in a given Binary Tree
    Given a binary tree and an integer X, the task is to find out all the occurrences of X in the given tree, and print its level and its position from left to right on that level. If X is not found, print -1. Examples: Input: X=35 10 / \ 20 30 / \ / \40 60 35 50Output: [(3, 3)]Explanation: Integer X=35
    7 min read
  • Print the middle nodes of each level of a Binary Tree
    Given a Binary Tree, the task is to print the middle nodes of each level of a binary tree. Considering M to be the number of nodes at any level, print (M/2)th node if M is odd. Otherwise, print (M/2)th node and ((M/2) + 1)th node. Examples: Input: Below is the given Tree: Output:12 35 1011 67 9Expla
    11 min read
  • Print all nodes except rightmost node of every level of the Binary Tree
    Given a binary tree, the task is to print all the nodes except the rightmost in every level of the tree. The root is considered at level 0, and rightmost node of any level is considered as a node at position 0.Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 / \ 7 8 / \ 9 10 Output: 2 4 5 7 9 Input: 1 / \ 2 3
    7 min read
  • Print extreme nodes of each level of Binary Tree in alternate order
    Given a binary tree, print nodes of extreme corners of each level but in alternate order.Example: For above tree, the output can be 1 2 7 8 31 - print rightmost node of 1st level - print leftmost node of 2nd level - print rightmost node of 3rd level - print leftmost node of 4th level - print rightmo
    10 min read
  • Difference between sums of odd position and even position nodes for each level of a Binary Tree
    Given a Binary Tree, the task is to find the absolute difference between the sums of odd and even positioned nodes. A node is said to be odd and even positioned if its position in the current level is odd and even respectively. Note that the first element of each row is considered as odd positioned.
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences