logo CodeStepByStep logo

limitPathSum

Language/Type: C++ binary trees pointers recursion

Write a function named limitPathSum that accepts a reference to a pointer to the root of a binary tree of integers. Your function should also accept an integer value representing a maximum, and remove nodes to guarantee that the sum of values on any path from the root to a node does not exceed that maximum. For example, if variable root points to the root of the tree below at left, the call of limitPathSum(root, 50); will require removing node 12 because the sum from the root down to that node is more than 50 (29 + 17 + -7 + 12 = 51). Similarly, we have to remove node 37 because its sum is (29 + 17 + 37 = 83). When you remove a node, you remove anything under it, so removing 37 also removes 16. We also remove the node with 14 because its sum is (29 + 15 + 14 = 58). If the data stored at the root is greater than the given maximum, remove all nodes, leaving an empty (nullptr) tree. Free the memory associated with each node you remove, but only remove the nodes that are necessary to remove.

root after limitPathSum(root, 50);
(29 (17 (-7 (11) (12)) (37 / (16))) (15 (4) (14 (-9) (19))))
(29 (17 (-7 (11))) (15 (4)))

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 use any auxiliary data structures to solve this problem (no array, vector, stack, queue, string, etc).

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.