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

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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 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 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 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             # 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)

Output:

5 7 11

My Personal Notes arrow_drop_up Small things always make you to think big

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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Improved By : princi singh

Article Tags :
Practice Tags :

Be the First to upvote.

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