Skip to content

Instantly share code, notes, and snippets.

@rishabh1403
Created July 30, 2016 09:19
Show Gist options
  • Save rishabh1403/7c21b8bcaddc5f68f87ba2e6d6365079 to your computer and use it in GitHub Desktop.
Save rishabh1403/7c21b8bcaddc5f68f87ba2e6d6365079 to your computer and use it in GitHub Desktop.
Recursive and iterative LevelOrder tree traversal
//TODO add recursive
import java.util.*;
//Node class
class Node{
int data;
Node left;
Node right;
Node(int data){
this.data = data;
this.left=null;
this.right = null;
}
}
public class LevelOrder {
public static void main(String args[]){
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
iterativeLevelOrder(root);
System.out.println();
//recursiveLevelOrder(root);
}
//recursive method
//iterative method
private static void iterativeLevelOrder(Node root) {
// TODO Auto-generated method stub
if(root == null)
return;
Queue<Node> q = new LinkedList<Node>();
q.offer(root);
while(!q.isEmpty()){
Node t = q.poll();
System.out.print(t.data+" ");
if(t.left != null)
q.offer(t.left);
if(t.right != null)
q.offer(t.right);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment