Skip to content

Instantly share code, notes, and snippets.

@anil477
Last active June 30, 2017 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anil477/4ad0a2ec527dc2e306b2b631ecc3e499 to your computer and use it in GitHub Desktop.
Save anil477/4ad0a2ec527dc2e306b2b631ecc3e499 to your computer and use it in GitHub Desktop.
Binary Tree Traversal - Level Order Using Queue
// prints the node value in binary tree at each level
// prints all the node value in binary tree together
// prints tree in binary order
import java.util.Stack;
import java.util.Queue;
import java.util.LinkedList;
class Node {
int data;
Node left, right;
public Node(int item) {
data = item;
left = null;
right = null;
}
}
class BinaryTree {
Node root;
void printLevelOrder()
{
Queue<Node> queue = new LinkedList<Node>();
queue.add(root);
while(!queue.isEmpty()) {
Node temp = queue.poll();
System.out.print(temp.data + " ");
if(temp.left != null) {
queue.add(temp.left);
}
if(temp.right != null) {
queue.add(temp.right);
}
}
}
void printLevelOrderPerLevel()
{
Queue<Node> queue = new LinkedList<Node>();
queue.add(root);
while(true){
int size = queue.size();
if(size == 0){
break;
}
while( size > 0 ) {
Node temp = queue.poll();
System.out.print(temp.data + " ");
if(temp.left != null) {
queue.add(temp.left);
}
if(temp.right != null) {
queue.add(temp.right);
}
size--;
}
System.out.println();
}
}
void spiralOrder()
{
Stack<Node> s1 = new Stack<Node>();
Stack<Node> s2 = new Stack<Node>();
s1.push(root);
while(!s1.isEmpty()|| !s2.isEmpty())
{
while(!s1.isEmpty())
{
Node temp = s1.pop();
System.out.print(" " + temp.data + " ");
if(temp.right != null) {
s2.push(temp.right);
}
if(temp.left != null) {
s2.push(temp.left);
}
}
while(!s2.isEmpty())
{
Node temp = s2.pop();
System.out.print(" " + temp.data + " ");
if(temp.left != null) {
s1.push(temp.left);
}
if(temp.right != null) {
s1.push(temp.right);
}
}
}
}
public static void main(String args[])
{
BinaryTree tree_level = new BinaryTree();
tree_level.root = new Node(1);
tree_level.root.left = new Node(2);
tree_level.root.right = new Node(3);
tree_level.root.left.left = new Node(4);
tree_level.root.left.right = new Node(5);
tree_level.root.right.left = new Node(6);
tree_level.root.right.right = new Node(7);
System.out.println("Level order traversal of binary tree is - ");
tree_level.printLevelOrder();
System.out.println();
System.out.println("Level order traversal of binary tree per level is - ");
tree_level.printLevelOrderPerLevel();
System.out.println(" Tree in Spiral Order ");
tree_level.spiralOrder();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment