From a9e8b6b1001832861c063b18ad1165b1bbe4be99 Mon Sep 17 00:00:00 2001 From: KyleScharnhorst Date: Sat, 7 Oct 2017 20:18:35 -0700 Subject: [PATCH] Add: level order traversal. Prints each level of the bst. I.e., Root -> its children -> its children's children -> and so on... --- data_structures/Trees/TreeTraversal.java | 30 +++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/data_structures/Trees/TreeTraversal.java b/data_structures/Trees/TreeTraversal.java index c4ff92d0..8dd0555a 100644 --- a/data_structures/Trees/TreeTraversal.java +++ b/data_structures/Trees/TreeTraversal.java @@ -3,6 +3,7 @@ * @author Varun Upadhyay (https://github.com/varunu28) * */ +import java.util.LinkedList; // Driver Program public class TreeTraversal { @@ -10,18 +11,25 @@ public class TreeTraversal { Node tree = new Node(5); tree.insert(3); tree.insert(7); + tree.insert(1); + tree.insert(9); - // Prints 3 5 7 + // Prints 1 3 5 7 9 tree.printInOrder(); System.out.println(); - // Prints 5 3 7 + // Prints 5 3 1 7 9 tree.printPreOrder(); System.out.println(); - // Prints 3 7 5 + // Prints 1 3 9 7 5 tree.printPostOrder(); System.out.println(); + + // Add a couple more nodes for print level test + // Print 5 3 7 1 9 + tree.printLevelOrder(); + System.out.println(); } } @@ -31,6 +39,7 @@ public class TreeTraversal { * printInOrder: LEFT -> ROOT -> RIGHT * printPreOrder: ROOT -> LEFT -> RIGHT * printPostOrder: LEFT -> RIGHT -> ROOT + * printLevelOrder: ROOT -> ROOT's CHILDREN -> ROOT's CHILDREN's CHILDREN -> etc */ class Node { Node left, right; @@ -88,5 +97,20 @@ class Node { } System.out.print(data + " "); } + + public void printLevelOrder() { + LinkedList queue = new LinkedList<>(); + queue.add(this); + while(!queue.isEmpty()) { + Node n = queue.poll(); + System.out.print(n.data + " "); + if (n.left != null) { + queue.add(n.left); + } + if (n.right != null) { + queue.add(n.right); + } + } + } }