Specific Level Order Traversal of Binary Tree
Last Updated :
25 Oct, 2024
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++
// 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
// 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
# 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#
// 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
// 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 + " ");
}
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.
Similar Reads
Perfect Binary Tree Specific Level Order Traversal
Given a Perfect Binary Tree like below: Print the level order of nodes in following specific manner: 1 2 3 4 7 5 6 8 15 9 14 10 13 11 12 16 31 17 30 18 29 19 28 20 27 21 26 22 25 23 24i.e. print nodes in level order but nodes should be from left and right side alternatively. Here 1st and 2nd levels
15+ min read
Perfect Binary Tree Specific Level Order Traversal | Set 2
Perfect Binary Tree using Specific Level Order Traversal in Set 1. The earlier traversal was from Top to Bottom. In this post, Bottom to Top traversal (asked in Amazon Interview | Set 120 â Round 1) is discussed. 16 31 17 30 18 29 19 28 20 27 21 26 22 25 23 24 8 15 9 14 10 13 11 12 4 7 5 6 2 3 1The
15+ min read
Double Order Traversal of a Binary Tree
Given a Binary Tree, the task is to find its Double Order Traversal. Double Order Traversal is a tree traversal technique in which every node is traversed twice in the following order: Visit the Node.Traverse the Left Subtree.Visit the Node.Traverse the Right Subtree.Examples:Input: Output: 1 7 4 4
6 min read
Boundary Level order traversal of a Binary Tree
Given a Binary Tree, the task is to print all levels of this tree in Boundary Level order traversal. Boundary Level order traversal: In this traversal, the first element of the level (starting boundary) is printed first, followed by last element (ending boundary). Then the process is repeated for th
11 min read
Flatten Binary Tree in order of Level Order Traversal
Given a Binary Tree, the task is to flatten it in order of Level order traversal of the tree. In the flattened binary tree, the left node of all the nodes must be NULL.Examples: Input: 1 / \ 5 2 / \ / \ 6 4 9 3 Output: 1 5 2 6 4 9 3 Input: 1 \ 2 \ 3 \ 4 \ 5 Output: 1 2 3 4 5 Approach: We will solve
7 min read
Preorder Traversal of Binary Tree
Preorder traversal is a tree traversal method that follows the Root-Left-Right order:The root node of the subtree is visited first.Next, the left subtree is recursively traversed.Finally, the right subtree is recursively traversed.How does Preorder Traversal work?Key Properties: Used in expression t
5 min read
Mix Order Traversal of a Binary Tree
Given a Binary Tree consisting of N nodes, the task is to print its Mix Order Traversal. Mix Order Traversal is a tree traversal technique, which involves any two of the existing traversal techniques like Inorder, Preorder and Postorder Traversal. Any two of them can be performed or alternate levels
13 min read
Postorder Traversal of Binary Tree
Postorder traversal is a tree traversal method that follows the Left-Right-Root order:The left subtree is visited first.The right subtree is visited next.The root node is processed last.How does Postorder Traversal work?Key Properties:It is used for tree deletion because subtrees are deleted before
5 min read
ZigZag Level Order Traversal of an N-ary Tree
Given a Generic Tree consisting of n nodes, the task is to find the ZigZag Level Order Traversal of the given tree.Note: A generic tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at most two children per node (left and right), a generic tree allow
8 min read
Inorder Traversal of Binary Tree
Inorder traversal is a depth-first traversal method that follows this sequence:Left subtree is visited first.Root node is processed next.Right subtree is visited last.How does Inorder Traversal work?Key Properties:If applied to a Binary Search Tree (BST), it returns elements in sorted order.Ensures
5 min read