In diis chapter, a single iterator class was created to perform any one of the three binary tree traversals. The user could specify which of the traversals to use by calling setPreorder, set Inorder, or setPostorde. An alternative implementation is based on creating a separate iterator class for each of the traversals. Also, as was mentioned in diis chapter, the space and time requirements of the traversal can be minimized if the traversals are based on nonrecursive algorithms.
For example, the following pseudocode demonstrates how the method inorderTraverse presented in this chapter can be modified slightly and called from the method next in the iterator. The original version of inorderTraverse used a queue to store the entire traversal. This version of the method will produce the next node in the traversal only as needed. It is therefore slightly different in diat the statement that queued a node is replaced with a return of the node.
+inorderTraverse(in treeNode:TreeNode):TreeltemType
//Nonrecursively traverses a binary tree
// inorder.
curr = treeNode // start at treeNode
done = false
while (!done) {
if (curr !=null) {
visitStack.push(curr)
// traverse the left subtree
curr = curr.leftChild
}
else {
if (!visitStack.isEmpty()) {
curr = visitStack.pop()
return curr.item
}
else {
done - true
} //end if
} //end if
} //end while
Implement an iterator class for each of the diree traversals using nonrecursive methods such that the storage requirements are never greater dian O (height of the tree).
We need at least 10 more requests to produce the solution.
0 / 10 have requested this problem solution
The more requests, the faster the answer.