Boundary Level order traversal of a Binary Tree
Last Updated :
05 Jan, 2023
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 the second and last-second element, till the complete level has been printed.
Examples:
Input:
1
/ \
12 13
/ \ / \
11 6 4 11
/ / \ / \
23 7 9 2 4
Output:
1
12 13
11 11 6 4
23 4 7 2 9
Input:
7
/ \
22 19
/ \ \
3 6 13
/ \ \ / \
1 5 8 1 4
/
23
Output:
7
22 19
3 13 6
1 4 5 1 8
23
Approach:
- In order to print level in Boundary Level order traversal, we need to first do the Level Order Traversal of the Binary tree to get the values at each level.
- Here a Queue data structure is used to store the levels of the Tree while doing the Level Order Traversal.
- Then for each level, the first element of the level (starting boundary) is printed first, followed by the last element (ending boundary). Then the process is repeated for the second and last-second element, till the complete level has been printed.
Below is the implementation of the above approach:
C++
// C++ program for printing a
// Levels of Binary Tree in a
// start end fashion
#include <bits/stdc++.h>
using namespace std;
// A Tree node
struct Node {
int key;
struct Node *left, *right;
};
// Utility function to create a new node
Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return (temp);
}
// Utility function to print level in
// start end fashion
void printLevelUtil(struct Node* queue[],
int index, int size)
{
while (index < size) {
cout << queue[index++]->key << " "
<< queue[size--]->key << " ";
}
if (index == size) {
cout << queue[index]->key << " ";
}
cout << endl;
}
// Utility function to print level in start
// end fashion in a given Binary tree
void printLevel(struct Node* node,
struct Node* queue[],
int index, int size)
{
// Print root node value
// as a single value in a
// binary tree
cout << queue[index]->key << endl;
// Level order traversal of Tree
while (index < size) {
int curr_size = size;
while (index < curr_size) {
struct Node* temp = queue[index];
if (temp->left != NULL) {
queue[size++] = temp->left;
}
if (temp->right != NULL) {
queue[size++] = temp->right;
}
index++;
}
// Print level in a desire fashion
printLevelUtil(queue, index, size - 1);
}
}
// Function to find total no of nodes
int findSize(struct Node* node)
{
if (node == NULL)
return 0;
return 1
+ findSize(node->left)
+ findSize(node->right);
}
// Function to print level in start end
// fashion in a given binary tree
void printLevelInStartEndFashion(
struct Node* node)
{
int t_size = findSize(node);
struct Node* queue[t_size];
queue[0] = node;
printLevel(node, queue, 0, 1);
}
// Driver Code
int main()
{
/* 10
/ \
13 13
/ \
14 15
/ \ / \
21 22 22 21
/
8 */
// Create Binary Tree as shown
Node* root = newNode(10);
root->left = newNode(13);
root->right = newNode(13);
root->right->left = newNode(14);
root->right->right = newNode(15);
root->right->left->left = newNode(21);
root->right->left->right = newNode(22);
root->right->right->left = newNode(22);
root->right->right->right = newNode(21);
root->right->right->right->left = newNode(8);
// Print Levels In Start End Fashion
printLevelInStartEndFashion(root);
return 0;
}
Java
// Java program for printing a
// Levels of Binary Tree in a
// start end fashion
class GFG{
// A Tree node
static class Node {
int key;
Node left, right;
};
// Utility function to create a new node
static Node newNode(int key)
{
Node temp = new Node();
temp.key = key;
temp.left = temp.right = null;
return (temp);
}
// Utility function to print level in
// start end fashion
static void printLevelUtil(Node queue[],
int index, int size)
{
while (index < size) {
System.out.print(queue[index++].key+ " "
+ queue[size--].key+ " ");
}
if (index == size) {
System.out.print(queue[index].key+ " ");
}
System.out.println();
}
// Utility function to print level in start
// end fashion in a given Binary tree
static void printLevel(Node node,
Node queue[],
int index, int size)
{
// Print root node value
// as a single value in a
// binary tree
System.out.print(queue[index].key +"\n");
// Level order traversal of Tree
while (index < size) {
int curr_size = size;
while (index < curr_size) {
Node temp = queue[index];
if (temp.left != null) {
queue[size++] = temp.left;
}
if (temp.right != null) {
queue[size++] = temp.right;
}
index++;
}
// Print level in a desire fashion
printLevelUtil(queue, index, size - 1);
}
}
// Function to find total no of nodes
static int findSize(Node node)
{
if (node == null)
return 0;
return 1
+ findSize(node.left)
+ findSize(node.right);
}
// Function to print level in start end
// fashion in a given binary tree
static void printLevelInStartEndFashion(
Node node)
{
int t_size = findSize(node);
Node []queue = new Node[t_size];
queue[0] = node;
printLevel(node, queue, 0, 1);
}
// Driver Code
public static void main(String[] args)
{
/* 10
/ \
13 13
/ \
14 15
/ \ / \
21 22 22 21
/
8 */
// Create Binary Tree as shown
Node root = newNode(10);
root.left = newNode(13);
root.right = newNode(13);
root.right.left = newNode(14);
root.right.right = newNode(15);
root.right.left.left = newNode(21);
root.right.left.right = newNode(22);
root.right.right.left = newNode(22);
root.right.right.right = newNode(21);
root.right.right.right.left = newNode(8);
// Print Levels In Start End Fashion
printLevelInStartEndFashion(root);
}
}
// This code is contributed by Princi Singh
Python3
# Python3 program for printing a
# Levels of Binary Tree in a
# start end fashion
# A Tree node
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
# function to create a
# new node
def newNode(key):
temp = Node(key);
return temp;
# Utility function to print
# level in start end fashion
def printLevelUtil(queue,
index, size):
while (index < size):
print(str(queue[index].key) + ' ' +
str(queue[size].key), end = ' ')
size -= 1
index += 1
if (index == size):
print(queue[index].key,
end = ' ')
print()
# Utility function to print
# level in start end fashion
# in a given Binary tree
def printLevel(node, queue,
index, size):
# Print root node value
# as a single value in a
# binary tree
print(queue[index].key)
# Level order traversal
# of Tree
while (index < size):
curr_size = size;
while (index < curr_size):
temp = queue[index];
if (temp.left != None):
queue[size] = temp.left;
size += 1
if (temp.right != None):
queue[size] = temp.right;
size += 1
index += 1
# Print level in a desire
# fashion
printLevelUtil(queue, index,
size - 1);
# Function to find total
# no of nodes
def findSize(node):
if (node == None):
return 0;
return (1 + findSize(node.left) +
findSize(node.right));
# Function to print level in start
# end fashion in a given binary tree
def printLevelInStartEndFashion(node):
t_size = findSize(node);
queue=[0 for i in range(t_size)];
queue[0] = node;
printLevel(node, queue, 0, 1);
# Driver code
if __name__=="__main__":
''' 10
/ \
13 13
/ \
14 15
/ \ / \
21 22 22 21
/
8 '''
# Create Binary Tree as shown
root = newNode(10);
root.left = newNode(13);
root.right = newNode(13);
root.right.left = newNode(14);
root.right.right = newNode(15);
root.right.left.left = newNode(21);
root.right.left.right = newNode(22);
root.right.right.left = newNode(22);
root.right.right.right = newNode(21);
root.right.right.right.left = newNode(8);
# Print Levels In Start End Fashion
printLevelInStartEndFashion(root);
# This code is contributed by Rutvik_56
C#
// C# program for printing a
// Levels of Binary Tree in a
// start end fashion
using System;
class GFG{
// A Tree node
class Node {
public int key;
public Node left, right;
};
// Utility function to create a new node
static Node newNode(int key)
{
Node temp = new Node();
temp.key = key;
temp.left = temp.right = null;
return (temp);
}
// Utility function to print level in
// start end fashion
static void printLevelUtil(Node []queue,
int index, int size)
{
while (index < size) {
Console.Write(queue[index++].key+ " "
+ queue[size--].key+ " ");
}
if (index == size) {
Console.Write(queue[index].key+ " ");
}
Console.WriteLine();
}
// Utility function to print level in start
// end fashion in a given Binary tree
static void printLevel(Node node,
Node []queue,
int index, int size)
{
// Print root node value
// as a single value in a
// binary tree
Console.Write(queue[index].key +"\n");
// Level order traversal of Tree
while (index < size) {
int curr_size = size;
while (index < curr_size) {
Node temp = queue[index];
if (temp.left != null) {
queue[size++] = temp.left;
}
if (temp.right != null) {
queue[size++] = temp.right;
}
index++;
}
// Print level in a desire fashion
printLevelUtil(queue, index, size - 1);
}
}
// Function to find total no of nodes
static int findSize(Node node)
{
if (node == null)
return 0;
return 1
+ findSize(node.left)
+ findSize(node.right);
}
// Function to print level in start end
// fashion in a given binary tree
static void printLevelInStartEndFashion(
Node node)
{
int t_size = findSize(node);
Node []queue = new Node[t_size];
queue[0] = node;
printLevel(node, queue, 0, 1);
}
// Driver Code
public static void Main(String[] args)
{
/* 10
/ \
13 13
/ \
14 15
/ \ / \
21 22 22 21
/
8 */
// Create Binary Tree as shown
Node root = newNode(10);
root.left = newNode(13);
root.right = newNode(13);
root.right.left = newNode(14);
root.right.right = newNode(15);
root.right.left.left = newNode(21);
root.right.left.right = newNode(22);
root.right.right.left = newNode(22);
root.right.right.right = newNode(21);
root.right.right.right.left = newNode(8);
// Print Levels In Start End Fashion
printLevelInStartEndFashion(root);
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
// JavaScript program for printing a
// Levels of Binary Tree in a
// start end fashion
// A Tree node
class Node {
constructor()
{
this.key = 0;
this.left = null;
this.right = null;
}
};
// Utility function to create a new node
function newNode(key)
{
var temp = new Node();
temp.key = key;
temp.left = temp.right = null;
return (temp);
}
// Utility function to print level in
// start end fashion
function printLevelUtil(queue, index, size)
{
while (index < size) {
document.write(queue[index++].key+ " "
+ queue[size--].key+ " ");
}
if (index == size) {
document.write(queue[index].key+ " ");
}
document.write("<br>");
}
// Utility function to print level in start
// end fashion in a given Binary tree
function printLevel(node, queue, index, size)
{
// Print root node value
// as a single value in a
// binary tree
document.write(queue[index].key +"<br>");
// Level order traversal of Tree
while (index < size) {
var curr_size = size;
while (index < curr_size) {
var temp = queue[index];
if (temp.left != null) {
queue[size++] = temp.left;
}
if (temp.right != null) {
queue[size++] = temp.right;
}
index++;
}
// Print level in a desire fashion
printLevelUtil(queue, index, size - 1);
}
}
// Function to find total no of nodes
function findSize(node)
{
if (node == null)
return 0;
return 1
+ findSize(node.left)
+ findSize(node.right);
}
// Function to print level in start end
// fashion in a given binary tree
function printLevelInStartEndFashion( node)
{
var t_size = findSize(node);
var queue = Array(t_size);
queue[0] = node;
printLevel(node, queue, 0, 1);
}
// Driver Code
/* 10
/ \
13 13
/ \
14 15
/ \ / \
21 22 22 21
/
8 */
// Create Binary Tree as shown
var root = newNode(10);
root.left = newNode(13);
root.right = newNode(13);
root.right.left = newNode(14);
root.right.right = newNode(15);
root.right.left.left = newNode(21);
root.right.left.right = newNode(22);
root.right.right.left = newNode(22);
root.right.right.right = newNode(21);
root.right.right.right.left = newNode(8);
// Print Levels In Start End Fashion
printLevelInStartEndFashion(root);
</script>
Output: 10
13 13
14 15
21 21 22 22
8
Time complexity: The time complexity of this implementation is also O(N), as the printLevel function visits each node in the tree exactly once and performs a constant amount of work for each node.
Auxiliary Space: The Auxiliary Space of this implementation is O(N), where N is the number of nodes in the tree. This is because the printLevel function uses an array of size N to store the nodes at each level of the tree as it performs a level order traversal.
Similar Reads
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 Traversal of binary tree
Given a binary tree, the task is to find the boundary nodes of the binary tree Anti-Clockwise starting from the root.The boundary includes:left boundary (nodes on left excluding leaf nodes)leaves (consist of only the leaf nodes)right boundary (nodes on right excluding leaf nodes)The left boundary is
15+ min read
Boundary Root to Leaf Path traversal of a Binary Tree
Given a Binary Tree, the task is to print all Root to Leaf path of this tree in Boundary Root to Leaf path traversal. Boundary Root to Leaf Path Traversal: In this traversal, the first Root to Leaf path(Left boundary) is printed first, followed by the last Root to Leaf path (Right boundary) in Rever
15+ 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
Middle To Up-Down Order traversal of a Binary Tree
Given a binary tree, the task is to traverse this binary tree from the middle to the up-down order. In Middle to up-down order traversal, the following steps are performed: First, print the middle level of the tree.Then, print the elements at one level above the middle level of the tree.Then, print
15+ min read
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 Explan
8 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
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
Sideways traversal of a Complete Binary Tree
Given a Complete Binary Tree, the task is to print the elements in the following pattern. Let's consider the tree to be: The tree is traversed in the following way: The output for the above tree is: 1 3 7 11 10 9 8 4 5 6 2 Approach: The idea is to use the modified breadth first search function to st
15+ min read