Specific Level Order Traversal of Binary Tree
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:
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++ 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 Implementation of Specific level order
// traversal of a binary tree
import java.util.*;
class Node {
int data;
Node left;
Node right;
Node(int val) {
data = val;
left = null;
right = null;
}
}
// Function to perform specific level
// order traversal
class GfG {
static List<Integer> specificLevelOrder(Node root) {
// List to store the order of
// nodes at each level
List<Integer> result = new ArrayList<>();
// Check if the tree is empty
if (root == null) return result;
// Queue for level order traversal
Queue<Node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
int levelSize = q.size();
List<Integer> currentLevel
= new ArrayList<>();
// Traverse the current level
for (int i = 0; i < levelSize; i++) {
Node node = q.poll();
currentLevel.add(node.data);
// Push left and right children
// to the queue
if (node.left != null) q.add(node.left);
if (node.right != null) q.add(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.add(currentLevel.get(left));
break;
}
result.add(currentLevel.get(left++));
result.add(currentLevel.get(right--));
}
}
return result;
}
public static void main(String[] args) {
// 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);
List<Integer> result = specificLevelOrder(root);
for (int num : result) {
System.out.print(num + " ");
}
}
}
# Python Implementation of Specific level order
# traversal of a binary tree
from collections import deque
class Node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
# Function to perform specific level
# order traversal
def specific_level_order(root):
# Check if the tree is empty
if root is None:
return
# Queue for level order traversal
q = deque([root])
# List to store the order of
# nodes at each level
result = []
while q:
level_size = len(q)
current_level = []
# Traverse the current level
for _ in range(level_size):
node = q.popleft()
current_level.append(node.data)
# Push left and right children
# to the queue
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
# Print the current level in
# specific order
left = 0
right = len(current_level) - 1
while left <= right:
# Print the first element
# from the left
if left == right:
result.append(current_level[left])
break
result.append(current_level[left])
left += 1
result.append(current_level[right])
right -= 1
return result
if __name__ == "__main__":
# Representation of a binary tree
# 20
# / \
# 8 22
# / \
# 4 12
# / \
# 10 14
root = Node(20)
root.left = Node(8)
root.right = Node(22)
root.left.left = Node(4)
root.left.right = Node(12)
root.left.right.left = Node(10)
root.left.right.right = Node(14)
result = specific_level_order(root)
for num in result:
print(num, end=" ")
print()
// C# Implementation of Specific level order
// traversal of a binary tree
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node(int val) {
data = val;
left = null;
right = null;
}
}
class GfG {
// Function to perform specific level
// order traversal
static List<int> SpecificLevelOrder(Node root) {
// List to store the order of
// nodes at each level
List<int> result = new List<int>();
// Check if the tree is empty
if (root == null) return result;
// Queue for level order traversal
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
while (q.Count > 0) {
int levelSize = q.Count;
List<int> currentLevel = new List<int>();
// Traverse the current level
for (int i = 0; i < levelSize; i++) {
Node node = q.Dequeue();
currentLevel.Add(node.data);
// Push left and right children to the queue
if (node.left != null) q.Enqueue(node.left);
if (node.right != null) q.Enqueue(node.right);
}
// Print the current level in specific order
int left = 0;
int right = currentLevel.Count - 1;
while (left <= right) {
// Print the first element from the left
if (left == right) {
result.Add(currentLevel[left]);
break;
}
result.Add(currentLevel[left++]);
result.Add(currentLevel[right--]);
}
}
return result;
}
static void Main(string[] args) {
// 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);
List<int> result = SpecificLevelOrder(root);
foreach (int num in result) {
Console.Write(num + " ");
}
}
}
// JavaScript Implementation of Specific level order
// traversal of a binary tree
class Node {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
}
}
// Function to perform specific level
// order traversal
function specificLevelOrder(root) {
// Array to store the order of
// nodes at each level
const result = [];
// Check if the tree is empty
if (!root) return;
const q = [];
q.push(root);
while (q.length > 0) {
const levelSize = q.length;
const currentLevel = [];
// Traverse the current level
for (let i = 0; i < levelSize; i++) {
const node = q.shift();
currentLevel.push(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
let left = 0;
let right = currentLevel.length - 1;
while (left <= right) {
// Print the first element from the left
if (left === right) {
result.push(currentLevel[left]);
break;
}
result.push(currentLevel[left++]);
result.push(currentLevel[right--]);
}
}
return result;
}
// Representation of a binary tree
// 20
// / \
// 8 22
// / \
// 4 12
// / \
// 10 14
const 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);
const result = specificLevelOrder(root);
for (let num of result) {
console.log(num + " ");
}
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.