Added level order traversal, and more nodes in main method

This commit is contained in:
Miki Pokryvailo 2017-09-28 14:11:35 -04:00
parent 0aee19d427
commit 1e52ba37c3

View File

@ -1,3 +1,5 @@
import java.util.LinkedList;
/**
*
* @author Varun Upadhyay (https://github.com/varunu28)
@ -9,19 +11,27 @@ public class TreeTraversal {
public static void main(String[] args) {
Node tree = new Node(5);
tree.insert(3);
tree.insert(2);
tree.insert(7);
tree.insert(4);
tree.insert(6);
tree.insert(8);
// Prints 3 5 7
tree.printInOrder();
System.out.println();
// Prints 5 3 7
System.out.println("Pre order traversal:");
tree.printPreOrder();
System.out.println();
// Prints 3 7 5
System.out.println("In order traversal:");
tree.printInOrder();
System.out.println();
System.out.println("Post order traversal:");
tree.printPostOrder();
System.out.println();
System.out.println("Level order traversal:");
tree.printLevelOrder();
System.out.println();
}
}
@ -88,5 +98,19 @@ class Node {
}
System.out.print(data + " ");
}
}
public void printLevelOrder() {
LinkedList<Node> queue = new LinkedList<>();
queue.add(this);
while (queue.size() > 0) {
Node head = queue.remove();
System.out.print(head.data + " ");
if (head.left != null) {
queue.add(head.left);
}
if (head.right != null) {
queue.add(head.right);
}
}
}
}