Question: The program of Figs. 21.15 and 21.16 illustrated three recursive methods of traversing a binary treeinorder, preorder and postorder traversals. This exercise presents the level-order

The program of Figs. 21.15 and 21.16 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 shown in Fig. 21.22. Write method levelOrder to perform a level-order traversal of a binary tree object. Modify the program of Figs. 21.15 and 21.16 to use this method.

Fig. 21.22

I 2 3 4 5 6 7 8 9 10 II Insert the root node in the queue. While there are nodes left in the queue, do the

Fig. 21.15I // Fig. 21.15: Tree.java 2 // TreeNode and Tree class declarations for a binary search tree. 3 package

Fig. 21.16

I // Fig. 21.16: TreeTest.java 2 // Binary tree test program. 3 import java.security.SecureRandom; import

I 2 3 4 5 6 7 8 9 10 II Insert the root node in the queue. 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.

Step by Step Solution

3.42 Rating (158 Votes )

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

TreeNode class definition class TreeNode package access members TreeNode leftNode E data node value ... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Java How To Program Late Objects Questions!