Added comments to level order traversal method, and samples in main method.

This commit is contained in:
Miki Pokryvailo 2017-10-05 16:27:54 -04:00
parent 1e52ba37c3
commit 6823278618

View File

@ -1,10 +1,10 @@
import java.util.LinkedList; import java.util.LinkedList;
/** /**
* *
* @author Varun Upadhyay (https://github.com/varunu28) * @author Varun Upadhyay (https://github.com/varunu28)
* *
*/ */
// Driver Program // Driver Program
public class TreeTraversal { public class TreeTraversal {
@ -17,18 +17,19 @@ public class TreeTraversal {
tree.insert(6); tree.insert(6);
tree.insert(8); tree.insert(8);
// Prints 5 3 2 4 7 6 8
System.out.println("Pre order traversal:"); System.out.println("Pre order traversal:");
tree.printPreOrder(); tree.printPreOrder();
System.out.println(); System.out.println();
// Prints 2 3 4 5 6 7 8
System.out.println("In order traversal:"); System.out.println("In order traversal:");
tree.printInOrder(); tree.printInOrder();
System.out.println(); System.out.println();
// Prints 2 4 3 6 8 7 5
System.out.println("Post order traversal:"); System.out.println("Post order traversal:");
tree.printPostOrder(); tree.printPostOrder();
System.out.println(); System.out.println();
// Prints 5 3 7 2 4 6 8
System.out.println("Level order traversal:"); System.out.println("Level order traversal:");
tree.printLevelOrder(); tree.printLevelOrder();
System.out.println(); System.out.println();
@ -36,12 +37,13 @@ public class TreeTraversal {
} }
/** /**
* The Node class which initializes a Node of a tree * The Node class which initializes a Node of a tree
* Consists of all 3 traversal methods: printInOrder, printPostOrder & printPreOrder * Consists of all 3 traversal methods: printInOrder, printPostOrder & printPreOrder
* printInOrder: LEFT -> ROOT -> RIGHT * printInOrder: LEFT -> ROOT -> RIGHT
* printPreOrder: ROOT -> LEFT -> RIGHT * printPreOrder: ROOT -> LEFT -> RIGHT
* printPostOrder: LEFT -> RIGHT -> ROOT * printPostOrder: LEFT -> RIGHT -> ROOT
*/ * printLevelOrder: Prints by level (starting at root), from left to right.
*/
class Node { class Node {
Node left, right; Node left, right;
int data; int data;
@ -99,18 +101,23 @@ class Node {
System.out.print(data + " "); System.out.print(data + " ");
} }
/**
* O(n) time algorithm.
* Uses O(n) space to store nodes in a queue to aid in traversal.
*/
public void printLevelOrder() { public void printLevelOrder() {
LinkedList<Node> queue = new LinkedList<>(); LinkedList<Node> queue = new LinkedList<>();
queue.add(this); queue.add(this);
while (queue.size() > 0) { while (queue.size() > 0) {
Node head = queue.remove(); Node head = queue.remove();
System.out.print(head.data + " "); System.out.print(head.data + " ");
if (head.left != null) { // Add children of recently-printed node to queue, if they exist.
queue.add(head.left); if (head.left != null) {
} queue.add(head.left);
if (head.right != null) { }
queue.add(head.right); if (head.right != null) {
} queue.add(head.right);
} }
} }
}
} }