Skip to content

Instantly share code, notes, and snippets.

@rishi93
Last active December 16, 2017 07:01
Show Gist options
  • Select an option

  • Save rishi93/3cefa6cbf98a253739132afaa43212c7 to your computer and use it in GitHub Desktop.

Select an option

Save rishi93/3cefa6cbf98a253739132afaa43212c7 to your computer and use it in GitHub Desktop.
Binary Tree Level Order Traversal
import java.util.Queue;
import java.util.LinkedList;
class Node{
int data;
Node left, right;
Node(int data){
this.data = data;
this.left = null;
this.right = null;
}
}
class BinaryTree{
Node root;
void printLevelOrder(){
Queue<Node> queue = new LinkedList<Node>();
queue.add(root);
while(queue.isEmpty() == false){
Node current = queue.poll();
System.out.print(current.data + " ");
if(current.left != null){
queue.add(current.left);
}
if(current.right != null){
queue.add(current.right);
}
}
System.out.println();
}
}
public class Test{
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 the tree is:");
tree.printLevelOrder();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment