Skip to content

Added level order traversal, and more nodes in main method #103

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 18, 2017
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 30 additions & 6 deletions data_structures/Trees/TreeTraversal.java
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import java.util.LinkedList;

/**
*
* @author Varun Upadhyay (https://github.com/varunu28)
Expand All @@ -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("Pre order traversal:");
tree.printPreOrder();
System.out.println();

// Prints 5 3 7
tree.printPreOrder();
System.out.println("In order traversal:");
tree.printInOrder();
System.out.println();

// Prints 3 7 5
System.out.println("Post order traversal:");
tree.printPostOrder();
System.out.println();

System.out.println("Level order traversal:");
tree.printLevelOrder();
System.out.println();
}
}

Expand Down Expand Up @@ -88,5 +98,19 @@ public void printPostOrder() {
}
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);
}
}
}
}