Wrirte a leveOrderTraverse method that prints the nodes of a

Wrirte a leveOrderTraverse method that prints the nodes of a binary search tree in the order that they are visited. It must include a non-recursive algorithm by the use of a queue to keep track of the nodes. Program needs to be done in Java.

Solution

Hi, Please find my implementation.

Please let me know in case of any issue.

// function to print level order of tree
public static void leveOrderTraverse(Node root) {

// creating an Queue Object
Queue<Node> queue = new LinkedList<Node>();
queue.add(root); // putting root of tree in queue
while (!queue.isEmpty()) // iterate till queue is not empty
{

/* removes the present head.
Node tempNode = queue.poll();
System.out.print(tempNode.data + \" \");

/*If left child is not null then enqueue left child */
if (tempNode.left != null) {
queue.add(tempNode.left);
}

/*If right child is not null then enqueue right child */
if (tempNode.right != null) {
queue.add(tempNode.right);
}
}
}

Wrirte a leveOrderTraverse method that prints the nodes of a binary search tree in the order that they are visited. It must include a non-recursive algorithm by

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site