logo CodeStepByStep logo


Language/Type: C++ binary trees pointers recursion
Related Links:
Author: Marty Stepp (on 2016/12/03)

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);



          /      \
      19           65
     /  \         /
   54    32     23
          /      \
      19           65
     /  \            \
   32    54           23

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: 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. Your solution must be recursive.

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

struct BinaryTreeNode {
    int data;
    BinaryTreeNode* left;
    BinaryTreeNode* right;
Type your C++ solution code here:

This is a function problem. Write a C++ function as described. Do not write a complete program; just the function(s) above.

You must log in before you can solve this problem.

Log In

Need help?

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.

© Marty Stepp, all rights reserved.