logo CodeStepByStep logo

swapChildrenAtLevel

Language/Type: C++ binary trees pointers recursion

Write a function named swapChildrenAtLevel that manipulates a binary tree of BinaryTreeNode structures representing an unordered binary tree. Your function should accept two parameters: a reference to a pointer to the root of a tree, and an integer k, and should swap the left and right children of all nodes at level k. In other words, after your function is run, any node at level (k+1) that used to be its parent's left child should now be its parent's right child and vice versa. For this problem, the overall root of a tree is defined to be at level 1, its children are at level 2, etc. The table below shows the result of calling this member function on a particular tree.

level tree after swapChildrenAtLevel(tree, 2);
1

2

3

4
             42
          /      \
      19           65
     /  \         /
   54    32     23
        /
      12
             42
          /      \
      19           65
     /  \            \
   32    54           23
  /
12

If k is 0 or less than 0, your function should throw an integer exception. If the tree is empty or does not have any nodes at the given level or deeper, it should not be affected by a call to your function.

Constraints: You must implement your function recursively and without using loops. For efficiency, your function should not traverse any parts of the tree that it does not need to traverse. Specifically, you should not access any nodes lower than level (k+1), because there is nothing there that would be changed. Do not use any auxiliary data structures to solve this problem (no array, vector, stack, queue, string, etc). You may define helper functions to solve this problem. You should not construct any new tree node objects or change the data of any nodes, though you can declare pointers if you like.

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.