We recall that the coPreOrder traversal is like the preOrder except that we swap
ID: 3569882 • Letter: W
Question
We recall that the coPreOrder traversal is like the preOrder except that we swap the calls to the left and right subtrees. The method below prints the nodes of a binary tree in co-preorder // print the tree elements in co-preorder public void printInCoPreOrder() { System.out.println(element); // print the root if (right != null) right.printInCoPreOrder(); // traverse the right subtree if (left != null) left.printInCoPreOrder(); // traverse the left subtree } Write the iterative method public void iterativePrintInCoPreOrder() that prints the elements of the tree in co-preorder, by removing the recursive calls from printInCoPreOrder.
Explanation / Answer
public void iterativePrintInCoPreOrder()
{
if( root == null ) return;
Stack<Node> stack = new Stack<Node>( );
stack.push( root );
while( ! stack.isEmpty( ) ) {
Node current = stack.pop( );
if( current.right != null ) stack.push( current.right );
if( current.left != null ) stack.push( current.left );
System.out.println( current.element);
}
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.