logo CodeStepByStep logo

limitLeaves

Language/Type: C++ binary trees pointers recursion

Write a function named limitLeaves that removes nodes from a tree to guarantee that all leaf nodes store values that are greater than a given value. Your function accepts two parameters: a reference to a pointer to a BinaryTreeNode representing the root of the tree, and an integer n. You should remove nodes from the tree to guarantee that all leaf nodes store values that are greater than n. (In other words, no leaves with values less than or equal to n should remain after the call.)

For example, suppose a variable named tree points to the root of the tree below. If we then make the call of limitLeaves(tree, 20); , your function must guarantee that all leaf node values are greater than 20. So it must remove the leaves that store 8, 12, and 20. But notice that removing the 12 leaf makes the node with value 17 into a leaf. This new leaf is also not larger than 20, so it must also be removed. Thus, we end up with the tree below at right.

tree before call
            13
          /    \
      18         10
     /          /  \
   82         17    23
  /  \         \      \
92    8         12     20
after call of limitLeaves(tree, 20);
            13
          /    \
      18         10
     /             \
   82               23
  /
92

Notice that the nodes storing 13, 18, and 10 remain even though those values are not greater than 20 because they are branch nodes. Also notice that you might be required to remove nodes at many levels. For example, if the node storing 23 instead had stored the value 14, then we would have removed it as well, which would have led us to remove the node storing 10. Your function should remove the minimum number of nodes that satisfies the constraint that all leaf nodes store values greater than the given n.

Constraints: You must implement your function recursively and without using loops. Do not construct any new BinaryTreeNode objects in solving this problem (though you may create as many BinaryTreeNode* pointer variables as you like). Do not change the data field of any existing nodes of the tree. Do not use any auxiliary data structures to solve this problem (no array, vector, stack, queue, string, etc). Do not leak memory. If you remove a node from the tree, free its memory. Your solution should be at worst O(N) time, where N is the number of elements in the tree. You must also solve the problem using a single pass over the tree, not multiple passes.

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.