import java.util.LinkedList;
import java.util.Queue;
class Node {
int data;
Node left, right;
public Node(int item)
{
data = item;
left = null;
right = null;
}
}
class LevelOrderQueue {
Node root;
void printLevelOrder()
{
Queue<Node> queue = new LinkedList<Node>();
queue.add(root);
while (!queue.isEmpty()) {
Node tempNode = queue.poll();
System.out.print(tempNode.data + " ");
if (tempNode.left != null) {
queue.add(tempNode.left);
}
if (tempNode.right != null) {
queue.add(tempNode.right);
}
}
}
public static void main(String args[])
{
LevelOrderQueue tree_level = new LevelOrderQueue();
tree_level.root = new Node(1);
tree_level.root.left = new Node(2);
tree_level.root.right = new Node(3);
tree_level.root.left.left = new Node(4);
tree_level.root.left.right = new Node(5);
tree_level.printLevelOrder();
}
//Firstly we insert the root into the queue and iterate over
//the queue until the queue is empty.
//In every iteration, we will pop from the top of
// the queue and print the value at the top of the queue.
//Then, add its left and right nodes to the end of the queue
// Time Complexity: O(N) where n is the number of nodes in the binary tree.
//Space Complexity: O(N) where n is the number of nodes in the binary tree.
}
TechInsiderStory is place where you can find basic knowledge of various technology and framework. TechInsiderStory is provide free knowledge on various technology and framework.
Tree-Traverse-Order-Level-Queue
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment