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 1
The task is to print nodes in level order but nodes should be from left and right side alternatively and from bottom – up manner
5th level: 16(left), 31(right), 17(left), 30(right), … are printed.
4th level: 8(left), 15(right), 9(left), 14(right), … are printed.
v
3rd level: 4(left), 7(right), 5(left), 6(right) are printed.
1st and 2nd levels are trivial.
Approach 1:
The standard level order traversal idea slightly changes here.
- Instead of processing ONE node at a time, we will process TWO nodes at a time.
- For dequeued nodes, we push node’s left and right child into stack in following manner – 2nd node’s left child, 1st node’s right child, 2nd node’s right child and 1st node’s left child.
- And while pushing children into queue, the enqueue order will be: 1st node’s right child, 2nd node’s left child, 1st node’s left child and 2nd node’s right child. Also, when we process two queue nodes.
- Finally pop all Nodes from stack and prints them.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node *left, *right;
};
Node* newNode( int data)
{
Node* node = new Node;
node->data = data;
node->right = node->left = NULL;
return node;
}
void printSpecificLevelOrderUtil(Node* root, stack<Node*> &s)
{
if (root == NULL)
return ;
queue<Node*> q;
q.push(root->left);
q.push(root->right);
Node *first = NULL, *second = NULL;
while (!q.empty())
{
first = q.front();
q.pop();
second = q.front();
q.pop();
s.push(second->left);
s.push(first->right);
s.push(second->right);
s.push(first->left);
if (first->left->left != NULL)
{
q.push(first->right);
q.push(second->left);
q.push(first->left);
q.push(second->right);
}
}
}
void printSpecificLevelOrder(Node* root)
{
stack<Node*> s;
s.push(root);
if (root->left != NULL)
{
s.push(root->right);
s.push(root->left);
}
if (root->left->left != NULL)
printSpecificLevelOrderUtil(root, s);
while (!s.empty())
{
cout << s.top()->data << " " ;
s.pop();
}
}
int main()
{
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
cout << "Specific Level Order traversal of binary "
"tree is \n" ;
printSpecificLevelOrder(root);
return 0;
}
|
Java
import java.util.*;
class Node
{
int data;
Node left, right;
public Node( int data)
{
this .data = data;
left = right = null ;
}
}
class BinaryTree
{
Node root;
void printSpecificLevelOrderUtil(Node root, Stack<Node> s)
{
if (root == null )
return ;
Queue<Node> q = new LinkedList<Node>();
q.add(root.left);
q.add(root.right);
Node first = null , second = null ;
while (!q.isEmpty())
{
first = q.peek();
q.poll();
second = q.peek();
q.poll();
s.push(second.left);
s.push(first.right);
s.push(second.right);
s.push(first.left);
if (first.left.left != null )
{
q.add(first.right);
q.add(second.left);
q.add(first.left);
q.add(second.right);
}
}
}
void printSpecificLevelOrder(Node root)
{
Stack<Node> s = new Stack<Node>();
s.push(root);
if (root.left != null )
{
s.push(root.right);
s.push(root.left);
}
if (root.left.left != null )
printSpecificLevelOrderUtil(root, s);
while (!s.empty())
{
System.out.print(s.peek().data + " " );
s.pop();
}
}
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node( 1 );
tree.root.left = new Node( 2 );
tree.root.right = new Node( 3 );
System.out.println( "Specific Level Order Traversal "
+ "of Binary Tree is " );
tree.printSpecificLevelOrder(tree.root);
}
}
|
Python3
class Node:
s = []
q = []
elements = 0
def __init__( self , key):
self .data = key
self .left = None
self .right = None
def printSpecificLevelOrder( self , root):
self .s.append(root)
prnt = self .s.pop( 0 )
self .q.append(prnt.data)
if prnt.right:
self .s.append(root.right)
if prnt.left:
self .s.append(root.left)
while ( len ( self .s) > 0 ):
first = self .s.pop( 0 )
self .q.append(first.data)
second = self .s.pop( 0 )
self .q.append(second.data)
if first.left and second.right and first.right and second.left:
self .s.append(first.left)
self .s.append(second.right)
self .s.append(first.right)
self .s.append(second.left)
for elements in reversed ( self .q):
print (elements, end = " " )
root = Node( 1 )
root.left = Node( 2 )
root.right = Node( 3 )
print ( "Specific Level Order traversal of "
"binary tree is" )
root.printSpecificLevelOrder(root)
|
C#
using System;
using System.Collections.Generic;
public class Node
{
public int data;
public Node left, right;
public Node( int data)
{
this .data = data;
left = right = null ;
}
}
class GFG
{
public Node root;
public virtual void printSpecificLevelOrderUtil(Node root,
Stack<Node> s)
{
if (root == null )
{
return ;
}
LinkedList<Node> q = new LinkedList<Node>();
q.AddLast(root.left);
q.AddLast(root.right);
Node first = null , second = null ;
while (q.Count > 0)
{
first = q.First.Value;
q.RemoveFirst();
second = q.First.Value;
q.RemoveFirst();
s.Push(second.left);
s.Push(first.right);
s.Push(second.right);
s.Push(first.left);
if (first.left.left != null )
{
q.AddLast(first.right);
q.AddLast(second.left);
q.AddLast(first.left);
q.AddLast(second.right);
}
}
}
public virtual void printSpecificLevelOrder(Node root)
{
Stack<Node> s = new Stack<Node>();
s.Push(root);
if (root.left != null )
{
s.Push(root.right);
s.Push(root.left);
}
if (root.left.left != null )
{
printSpecificLevelOrderUtil(root, s);
}
while (s.Count > 0)
{
Console.Write(s.Peek().data + " " );
s.Pop();
}
}
public static void Main( string [] args)
{
GFG tree = new GFG();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
Console.WriteLine( "Specific Level Order Traversal " +
"of Binary Tree is " );
tree.printSpecificLevelOrder(tree.root);
}
}
|
Javascript
<script>
class Node
{
constructor(data) {
this .left = null ;
this .right = null ;
this .data = data;
}
}
let root;
function printSpecificLevelOrderUtil(root, s)
{
if (root == null )
return ;
let q = [];
q.push(root.left);
q.push(root.right);
let first = null , second = null ;
while (q.length > 0)
{
first = q[0];
q.shift();
second = q[0];
q.shift();
s.push(second.left);
s.push(first.right);
s.push(second.right);
s.push(first.left);
if (first.left.left != null )
{
q.push(first.right);
q.push(second.left);
q.push(first.left);
q.push(second.right);
}
}
}
function printSpecificLevelOrder(root)
{
let s = [];
s.push(root);
if (root.left != null )
{
s.push(root.right);
s.push(root.left);
}
if (root.left.left != null )
printSpecificLevelOrderUtil(root, s);
while (s.length > 0)
{
document.write(s[s.length - 1].data + " " );
s.pop();
}
}
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
document.write( "Specific Level Order Traversal "
+ "of Binary Tree is " + "</br>" );
printSpecificLevelOrder(root);
</script>
|
Output
Specific Level Order traversal of binary tree is
2 3 1
Time complexity: O(n), the time complexity of the above program is O(n) as we traverse each node of the tree exactly once.
Auxiliary Space: O(n), we use a queue and a stack to store the nodes of the tree, which makes the space complexity of the program O(n).
Approach 2: (Using vector)
- We will traverse each level top to down and we will push each level to stack from top to down
- so, that we can have finally down to up printed levels,
- we are having a level in a vector so we can print it in any defined way,
Implementation:
C++
#include<bits/stdc++.h>
using namespace std;
class Node
{
public :
int data;
Node* left;
Node* right;
Node( int value)
{
data = value;
left = NULL;
right = NULL;
}
};
void specific_level_order_traversal(Node* root)
{
queue <Node*> q;
stack < vector < int > > s;
q.push(root);
int sz;
while (!q.empty())
{
vector < int > v;
sz = q.size();
for ( int i=0;i<sz;++i)
{
Node* temp = q.front();
q.pop();
v.push_back(temp->data);
if (temp->left!=NULL)
q.push(temp->left);
if (temp->right!=NULL)
q.push(temp->right);
}
s.push(v);
}
while (!s.empty())
{
vector < int > v = s.top();
s.pop();
for ( int i=0,j=v.size()-1;i<j;++i)
{
cout<<v[i]<< " " <<v[j]<< " " ;
j--;
}
}
cout<<root->data;
}
int main()
{
Node *root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
cout << "Specific Level Order traversal of binary "
"tree is \n" ;
specific_level_order_traversal(root);
return 0;
}
|
Java
import java.util.*;
public class GFG
{
static class Node
{
int data;
Node left;
Node right;
Node( int value)
{
data = value;
left = null ;
right = null ;
}
};
static void specific_level_order_traversal(Node root)
{
Queue <Node> q= new LinkedList<>();
Stack <Vector<Integer>> s = new Stack<Vector<Integer>>();
q.add(root);
int sz;
while (q.size() > 0 )
{
Vector<Integer> v = new Vector<Integer>();
sz = q.size();
for ( int i = 0 ; i < sz; ++i)
{
Node temp = q.peek();
q.remove();
v.add(temp.data);
if (temp.left != null )
q.add(temp.left);
if (temp.right != null )
q.add(temp.right);
}
s.push(v);
}
while (s.size() > 0 )
{
Vector <Integer> v = s.peek();
s.pop();
for ( int i = 0 , j = v.size() - 1 ; i < j; ++i)
{
System.out.print(v.get(i) + " " +
v.get(j) + " " );
j--;
}
}
System.out.println(root.data);
}
public static void main(String args[])
{
Node root = new Node( 1 );
root.left = new Node( 2 );
root.right = new Node( 3 );
System.out.println( "Specific Level Order traversal" +
" of binary tree is" );
specific_level_order_traversal(root);
}
}
|
Python
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def specific_level_order_traversal(root) :
q = []
s = []
q.append(root)
sz = 0
while ( len (q) > 0 ) :
v = []
sz = len (q)
i = 0
while ( i < sz) :
temp = q[ 0 ]
q.pop( 0 )
v.append(temp.data)
if (temp.left ! = None ) :
q.append(temp.left)
if (temp.right ! = None ) :
q.append(temp.right)
i = i + 1
s.append(v)
while ( len (s) > 0 ) :
v = s[ - 1 ]
s.pop()
i = 0
j = len (v) - 1
while ( i < j) :
print (v[i] , " " , v[j] ,end = " " )
j = j - 1
i = i + 1
print (root.data)
root = Node( 1 )
root.left = Node( 2 )
root.right = Node( 3 )
print ( "Specific Level Order traversal of binary tree is" )
specific_level_order_traversal(root)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public class Node
{
public int data;
public Node left;
public Node right;
public Node( int value)
{
data = value;
left = null ;
right = null ;
}
};
static void specific_level_order_traversal(Node root)
{
Queue <Node> q = new Queue <Node>();
Stack <List< int >> s = new Stack<List< int >>();
q.Enqueue(root);
int sz;
while (q.Count > 0)
{
List< int > v = new List< int >();
sz = q.Count;
for ( int i = 0; i < sz; ++i)
{
Node temp = q.Peek();
q.Dequeue();
v.Add(temp.data);
if (temp.left != null )
q.Enqueue(temp.left);
if (temp.right != null )
q.Enqueue(temp.right);
}
s.Push(v);
}
while (s.Count > 0)
{
List< int > v = s.Peek();
s.Pop();
for ( int i = 0,
j = v.Count - 1; i < j; ++i)
{
Console.Write(v[i] + " " +
v[j] + " " );
j--;
}
}
Console.WriteLine(root.data);
}
public static void Main(String []args)
{
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
Console.WriteLine( "Specific Level Order traversal" +
" of binary tree is" );
specific_level_order_traversal(root);
}
}
|
Javascript
<script>
class Node
{
constructor(value)
{
this .data = value;
this .left = null ;
this .right = null ;
}
};
function specific_level_order_traversal(root)
{
var q = [];
var s = [];
q.push(root);
var sz;
while (q.length > 0)
{
var v = [];
sz = q.length;
for ( var i = 0; i < sz; ++i)
{
var temp = q[0];
q.shift();
v.push(temp.data);
if (temp.left != null )
q.push(temp.left);
if (temp.right != null )
q.push(temp.right);
}
s.push(v);
}
while (s.length > 0)
{
var v = s[s.length-1];
s.pop();
for ( var i = 0,
j = v.length - 1; i < j; ++i)
{
document.write(v[i] + " " +
v[j] + " " );
j--;
}
}
document.write(root.data);
}
var root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
document.write( "Specific Level Order traversal" +
" of binary tree is<br>" );
specific_level_order_traversal(root);
</script>
|
Output
Specific Level Order traversal of binary tree is
2 3 1
Time Complexity: O(n), as we are traversing each node of the binary tree once.
Auxiliary Space: O(n), as we are storing the nodes of each level in a vector and pushing them in a stack.
Last Updated :
29 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...