logo CodeStepByStep logo

levelTraversal

Language/Type: C++ binary trees pointers recursion

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

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

(8 (5) (7 (-3) (11)))

The call of levelTraversal(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.