Related questions with answers
The program of earlier figures illustrated three recursive methods of traversing a binary tree—inorder, preorder and postorder traversals. This exercise presents the level-order traversal of a binary tree, in which the node values are printed level by level, starting at the root node level. The nodes on each level are printed from left to right. The level-order traversal is not a recursive algorithm. It uses a queue object to control the output of the nodes. The algorithm is as follows:
a) Insert the root node in the queue.
b) While there are nodes left in the queue, do the following:
Get the next node in the queue.
Print the node’s value.
If the reference to the left child of the node is not null:
Insert the left child node in the queue.
If the reference to the right child of the node is not null:
Insert the right child node in the queue.
Write method levelOrder to perform a level-order traversal of a binary tree object. Modify the program of earlier figures to use this method.
Solution
VerifiedLevel-order tree printing:
We need to create a function that will add the left and right node to the queue and every new node should dequeue from the queue:
public void levelOrder() {
if(!isEmpty()) {
try {
Queue<TreeNode<T>> queue = new Queue<TreeNode<T>>();
queue.enqueue(root);
while(!queue.isEmpty()) {
TreeNode<T> node = queue.dequeue();
System.out.print(node.getData() + " ");
if(node.hasLeft())
queue.enqueue(node.getLeft());
if(node.hasRight())
queue.enqueue(node.getRight());
}
}
catch(QueueEmptyException e) {
System.out.println(e.getLocalizedMessage());
}
}
}
Create an account to view solutions
Create an account to view solutions
More related questions
1/4
1/7