Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

IN C PROGRAMMING Sample Cumulative Question #7 Note: The following problem is ex

ID: 3716547 • Letter: I

Question

IN C PROGRAMMING

Sample Cumulative Question #7 Note: The following problem is excerpted from the final exam I gave in Spring 2014. That particular semester, I had only alluded to the use of stacks to simulate recursion and had not shown them an example in class of how that might be done. (Wildcard) This semester, we've discussed the fact that stacks can be used to simulate recursion. It's time to give that a try. (This is somewhat new, but don't panic! You're capable of figuring this sort of thing out now!) Using stacks, write an iterative function that prints a preorder traversal of a binary tree. Recall that the recursive version is 6. void preorder (node root) if (rootNULL) return; / base case: if tree is empty, return printf("%d ", root->data); // first print this node's data preorder (root->left) // then process its left subtree // then process its right subtree preorder (root->right); To make your life easier, you can assume the following functions are already written for you, and when you call them, they modify a global stack: void push (node *myNode): // pushes a node pointer onto a global stack node *pop(void)i int isEmpty (void); // returns the node pointer popped off the global stack // returns 1 if the global stack is empty, 0 if not empty The stack is global so that you never have to worry about declaring it or passing it as a parameter to these functions. You may assume the stack is empty when your function is called, and you should leave it empty when your function terminates. void preorder (node *root)

Explanation / Answer

void preorder(node* root){

if (root == NULL)

       return;

stack.push(root);

    while (stack.empty() == 0)

    {

node* temp = stack.pop();

        printf ("%d ", temp->data);

        if (temp->right)

            stack.push(temp->right);

        if (temp->left)

            stack.push(temp->left);

    }



}