From 1e52ba37c31c7af29e2c36e6b93193f052ca9da6 Mon Sep 17 00:00:00 2001 From: Miki Pokryvailo Date: Thu, 28 Sep 2017 14:11:35 -0400 Subject: [PATCH] Added level order traversal, and more nodes in main method --- data_structures/Trees/TreeTraversal.java | 38 +++++++++++++++++++----- 1 file changed, 31 insertions(+), 7 deletions(-) diff --git a/data_structures/Trees/TreeTraversal.java b/data_structures/Trees/TreeTraversal.java index c4ff92d0..8e73134e 100644 --- a/data_structures/Trees/TreeTraversal.java +++ b/data_structures/Trees/TreeTraversal.java @@ -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 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); + } + } + } +}