2019-05-09 19:32:54 +08:00
|
|
|
package DataStructures.Trees;
|
|
|
|
|
2018-04-14 11:45:48 +08:00
|
|
|
import java.util.Queue;
|
|
|
|
import java.util.LinkedList;
|
2019-05-09 19:32:54 +08:00
|
|
|
|
|
|
|
|
2018-04-14 11:45:48 +08:00
|
|
|
/* Class to print Level Order Traversal */
|
|
|
|
public class LevelOrderTraversalQueue {
|
2019-05-09 19:32:54 +08:00
|
|
|
|
|
|
|
/* Class to represent Tree node */
|
|
|
|
class Node {
|
|
|
|
int data;
|
|
|
|
Node left, right;
|
|
|
|
|
|
|
|
public Node(int item) {
|
|
|
|
data = item;
|
|
|
|
left = null;
|
|
|
|
right = null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-04-14 11:45:48 +08:00
|
|
|
/* Given a binary tree. Print its nodes in level order
|
|
|
|
using array for implementing queue */
|
2020-05-25 05:21:28 +08:00
|
|
|
void printLevelOrder(Node root) {
|
2018-04-14 11:45:48 +08:00
|
|
|
Queue<Node> queue = new LinkedList<Node>();
|
|
|
|
queue.add(root);
|
2019-05-09 19:32:54 +08:00
|
|
|
while (!queue.isEmpty()) {
|
2018-04-14 11:45:48 +08:00
|
|
|
|
|
|
|
/* poll() removes the present head.
|
|
|
|
For more information on poll() visit
|
|
|
|
http://www.tutorialspoint.com/java/util/linkedlist_poll.htm */
|
|
|
|
Node tempNode = queue.poll();
|
|
|
|
System.out.print(tempNode.data + " ");
|
2019-05-09 19:32:54 +08:00
|
|
|
|
2018-04-14 11:45:48 +08:00
|
|
|
/*Enqueue left child */
|
|
|
|
if (tempNode.left != null) {
|
|
|
|
queue.add(tempNode.left);
|
|
|
|
}
|
2019-05-09 19:32:54 +08:00
|
|
|
|
2018-04-14 11:45:48 +08:00
|
|
|
/*Enqueue right child */
|
|
|
|
if (tempNode.right != null) {
|
|
|
|
queue.add(tempNode.right);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|