John P
John P

Reputation: 45

Remove all subtrees below depth k from the original tree?

I am absolutely stuck on this problem and have no idea where to go from where I am. It fails every test I give it but I am not sure how to fix it. The instructions are: remove all subtrees below depth k from the original tree

Releveant info: - DO NOT change the Node class. - DO NOT change the first line of any function: name, parameters, types. you may add new functions, but don't delete anything
- functions must be recursive - no loops - each function must have exactly one recursive helper function, which you add - each function must be independent --- do not call any function other than the helper - no fields (variables declared outside of a function)

If you think I left out any information/code, please let me know.

Relevant code:

private Node root;
private static class Node {
    public final int key;
    public Node left, right;
    public Node(int key) { this.key = key; }
}



public void removeBelowDepth(int k) {
    removeBelowDepthHelper(root, 0, k);
    }
private void removeBelowDepthHelper(Node node, int currentDepth, int k) {
    if (node == null) return;
    if (currentDepth == k) {
        node = null;
        return;
    }
    removeBelowDepthHelper(node.left, currentDepth + 1, k);
    removeBelowDepthHelper(node.right, currentDepth + 1, k);
    }

Upvotes: 2

Views: 766

Answers (1)

John P
John P

Reputation: 45

I took AJ's advice and simply changed the null call and it works flawlessly! Thank you guys so much!

public void removeBelowDepth(int k) {
        removeBelowDepthHelper(root, 0, k);
        }
        private void removeBelowDepthHelper(Node node, int currentDepth, int k) {
        if (node == null) return;
        if (currentDepth == k) {
            node.left = null;
            node.right = null;
            return;
        }
        removeBelowDepthHelper(node.left, currentDepth + 1, k);
        removeBelowDepthHelper(node.right, currentDepth + 1, k);
        }

Upvotes: 2

Related Questions