Open In App

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

Last Updated : 20 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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: 2 8

Input:
      2
    /   \
   4     15
  /     /
 45   17
Output: 4

 

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 1st node in every level as even 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 printOddLevelEvenNodes(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);
 
    printOddLevelEvenNodes(root);
 
    return 0;
}


Java




// Java implementation of the 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 printOddLevelEvenNodes(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);
 
    printOddLevelEvenNodes(root);
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 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 printOddLevelEvenNodes(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]
            # Print only even positioned
            # nodes of even levels
            if not evenLevel and 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)
 
    printOddLevelEvenNodes(root)


C#




// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG
{
class Node
{
    public int data;
    public Node left, right;
};
 
// Iterative method to do level order
// traversal line by line
static void printOddLevelEvenNodes(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);
 
    printOddLevelEvenNodes(root);
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
 
    // JavaScript implementation of the 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 printOddLevelEvenNodes(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);
   
    printOddLevelEvenNodes(root);
 
</script>


Output: 

2 8

 

Time Complexity: O(N), where N is number of nodes.
Auxiliary Space: O(N)



Previous Article
Next Article

Similar Reads

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 9 Input: 2 / \ 4 15 / / 45 17 Output: 15 Prerequi
8 min read
Print odd positioned nodes of even levels in level order of the given binary tree
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 Prer
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 Output: 2 45 Approach: To print nodes level by leve
8 min read
Modify Binary Tree by replacing all nodes at even and odd levels by their nearest even or odd perfect squares respectively
Given a Binary Tree consisting of N nodes, the task is to replace all the nodes that are present at even-numbered levels in a Binary Tree with their nearest even perfect square and replace nodes at odd-numbered levels with their nearest odd perfect square. Examples: Input: 5 / \ 3 2 / \ 16 19 Output: 9 / \ 4 4 / \ 9 25 Explanation: Level 1: Nearest
13 min read
Print nodes of a Binary Search Tree in Top Level Order and Reversed Bottom Level Order alternately
Given a Binary Search Tree, the task is to print the nodes of the BST in the following order: If the BST contains levels numbered from 1 to N then, the printing order is level 1, level N, level 2, level N - 1, and so on.The top-level order (1, 2, …) nodes are printed from left to right, while the bottom level order (N, N-1, ...) nodes are printed f
18 min read
Replace the odd positioned elements with their cubes and even positioned elements with their squares
Given an array arr[] of n elements, the task is to replace all the odd positioned elements with their cubes and even positioned elements with their squares i.e. the resultant array must be {arr[0]3, arr[1]2, arr[2]3, arr[3]2, ...}.Examples: Input: arr[]= {2, 3, 4, 5} Output: 8 9 64 25 Updated array will be {23, 32, 43, 52} -&gt; {8, 9, 64, 25}Input
5 min read
Increment odd positioned elements by 1 and decrement even positioned elements by 1 in an Array
Given an array arr[], the task is increment all the odd positioned elements by 1 and decrement all the even positioned elements by 1. Examples: Input: arr[] = {3, 6, 8} Output: 4 5 9 Input: arr[] = {9, 7, 3} Output: 10 6 4 Approach: Traverse the array element by element and if the current element's position is odd then increment it by 1 else decrem
5 min read
Difference between sums of odd level and even level nodes of a Binary Tree
Given a Binary Tree, find the difference between the sum of nodes at odd level and the sum of nodes at even level. Consider root as level 1, left and right children of root as level 2 and so on. For example, in the following tree, sum of nodes at odd level is (5 + 1 + 4 + 8) which is 18. And sum of nodes at even level is (2 + 6 + 3 + 7 + 9) which i
20 min read
Count nodes from all lower levels smaller than minimum valued node of current level for every level in a Binary Tree
Given a Binary Tree, the task is for each level is to print the total number of nodes from all lower levels which are less than or equal to every node present at that level. Examples: Input: Below is the given tree: 4 / \ 3 5 / \ / \ 10 2 3 1 Output: 4 3 0Explanation:Nodes in level 1 has 4 nodes as (3) in level 2 and (2, 3, 1) in level 3. Nodes in
11 min read
Print levels with odd number of nodes and even number of nodes
Given an N-ary tree, print all the levels with odd and even numbers of nodes in it. Examples: For example consider the following tree 1 - Level 1 / \ 2 3 - Level 2 / \ \ 4 5 6 - Level 3 / \ / 7 8 9 - Level 4The levels with odd number of nodes are: 1 3 4 The levels with even number of nodes are: 2Note: The level numbers starts from 1. That is, the r
16 min read
Article Tags :
Practice Tags :