Open In App

Specific Level Order Traversal of Binary Tree

Last Updated : 25 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Given a Binary Tree, the task is to perform a Specific Level Order Traversal of the tree such that at each level print 1st element then the last element, then 2nd element and 2nd last element, until all elements of that level are printed and so on.

Examples:

Input:

level-order-traversal-with-direction-change-after-every-two-levels


Output: 5 3 7 2 8 4 6 9 0 5 1 
Explanation: 
1st level:    5(root) 
2nd level:  3(left), 7(right) 
3rd level:  2(left), 8(right), 4(left), 6(right)
4th level:  9(left), 0(right), 5(left), 1(right)

Approach:

The idea is to traverse the binary tree in level order manner, collecting the node values for each level into an array. After collecting the values, print them in a specific order, alternating between the leftmost and rightmost nodes moving towards the center. This ensures that the output for each level reflects the desired sequence of first and last elements, second and second-last elements, and so on.

Follow the steps below to solve the problem:

  • Initialize a queue for level order traversal.
  • Traverse the tree level by level. Store each level into an array.
  • After processing a level, use two pointers to traverse the array from both ends, alternating between the leftmost and rightmost elements, and store them in a result array.
  • Finally, print the values stored in the result, which reflects the specific level order of the binary tree.

Below is the implementation of the above approach: 

C++
// C++ Implementation of Specific level order
//  traversal of a binary tree
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* left;
    Node* right;

    Node(int val) {
        data = val;
        left = nullptr;
        right = nullptr;
    }
};

// Function to perform specific level order traversal
vector<int> specificLevelOrder(Node* root) {
  
    // Vector to store the order of 
    // nodes at each level
    vector<int> result;
  
    // Check if the tree is empty
    if (!root) return result;

    // Queue for level order traversal
    queue<Node*> q;
    q.push(root);

    while (!q.empty()) {
        int levelSize = q.size();
        vector<int> currentLevel;

        // Traverse the current level
        for (int i = 0; i < levelSize; i++) {
            Node* node = q.front();
            q.pop();
            currentLevel.push_back(node->data);

            // Push left and right children to the queue
            if (node->left) q.push(node->left);
            if (node->right) q.push(node->right);
        }

        // Print the current level in specific order
        int left = 0;
        int right = currentLevel.size() - 1;
        while (left <= right) {
          
            // Print the first element from the left
            if (left == right) {
                result.push_back(currentLevel[left]);
                break;
            }
            result.push_back(currentLevel[left++]);  
            result.push_back(currentLevel[right--]); 
        }
    }

   return result;
}

int main() {
  
    // Representation of a binary tree
    //        20
    //      /    \
    //     8      22
    //    / \       
    //   4   12     
    //      / \
    //     10  14
    Node* root = new Node(20);
    root->left = new Node(8);
    root->right = new Node(22);
    root->left->left = new Node(4);
    root->left->right = new Node(12);
    root->left->right->left = new Node(10);
    root->left->right->right = new Node(14);

    vector<int> result = specificLevelOrder(root);
     for (int num : result) {
        cout << num << " ";
    }

    return 0;
}
Java Python C# JavaScript

Output
20 8 22 4 12 10 14 

Time Complexity: O(n), where n is the number of nodes in the binary tree, as each node is processed exactly once during level order traversal.
Auxiliary Space: O(n), due to the storage required for the queue during traversal and the result vector that holds the output values.



Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg