logo CodeStepByStep logo

zigzagTraversal

Language/Type: C++ binary trees pointers recursion

Write a function named zigzagTraversal that accepts a BinaryTreeNode pointer representing the root of a binary tree of integers and prints the tree's nodes in level-traversal order, alternating between left-to-right and right-to-left at each level. That is, print all nodes at level 1 (the root) from left to right, followed by all nodes at level 2 from right to left, then all nodes at level 3 from left to right, and so on. The contents of any given level should be printed all together on their own line separated by spaces.

For example, given a pointer tree that points to the root of the following binary tree:

(8 (5 (47 / (88)) (26)) (7 (-3 / (0)) (11 (33) (55))))

The call of zigzagTraversal(root); should print the following console output:

8
5 7
-3 11

If the tree is null (empty), print no output.

Assume that you are using the BinaryTreeNode structure as defined below:

struct BinaryTreeNode {
    int data;
    BinaryTreeNode* left;
    BinaryTreeNode* right;
};
Function: Write a C++ function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.