Skip to content

Instantly share code, notes, and snippets.

@ajinkyajawale14499
Last active July 28, 2019 19:34
Show Gist options
  • Save ajinkyajawale14499/c60e1617fcbcdfced06db0613cffff75 to your computer and use it in GitHub Desktop.
Save ajinkyajawale14499/c60e1617fcbcdfced06db0613cffff75 to your computer and use it in GitHub Desktop.
Reverse Level Order Traversal of Binary Tree using Stacks and Queues
import java.util.*;
class Node
{
int data;
Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
class BinaryTree
{
Node root;
public BinaryTree() { root = null; } //constructor
//function to print level order traversal of tree
void printLevelOrder()
{
int h = height(root);
int i;
for(i=h;i<=h;i--)
PrintGivenLevel(root,i);
}
//function for computing height
int height(Node root)
{
if(root == null)
return 0;
else
{
int Leftheight = height(root.left);
int Rightheight = height(root.right);
//larger one
if(Leftheight > Rightheight)
return (Leftheight + 1);
else return (Rightheight + 1);
}
}
/* Print nodes at the given level */
void PrintGivenLevel (Node root ,int level)
{
if (root == null)
return;
if (level == 1)
System.out.print(root.data + " ");
else if (level > 1)
{
PrintGivenLevel(root.left, level-1);
PrintGivenLevel(root.right, level-1);
}
}
}
public class Main {
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);
tree.root.left.left= new Node(4);
tree.root.left.right= new Node(5);
System.out.println("Level order traversal of binary tree is ");
tree.printLevelOrder();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment