-3

I have a class that uses an internal binary tree as a data structure. I have a weird problem. I'm recursively looking for a specific node. If the node is found I want the code to return the reference to it. The problem: After return it's always null! But why?

private HeapNode getHeapNode(double key) {
    //ELEMENT IS NOT AVAILABLE HERE, NULL-Pointer, ALWAYS
    return getHeapNodeRec(key, rootHeapNode);
}

private HeapNode getHeapNodeRec(double key, HeapNode curr) {
    if (curr == null) {
        return null;
    }
    if (curr.getKey() == key) {
        //ELEMENT IS AVAILABLE HERE, I can access its data!
        return curr;
    }
    else {
        getHeapNodeRec(key, curr.getLeft());
        getHeapNodeRec(key, curr.getRight());
    }
    return null;
} 
phip1611
  • 5,460
  • 4
  • 30
  • 57

2 Answers2

1

The reason you’re getting null is because you’re tossing the node away after you start stepping back out:

else {
    getHeapNodeRec(key, curr.getLeft());
    getHeapNodeRec(key, curr.getRight());
}
return null;

You search the left and the right nodes, but then after getting the results of that search, you don’t preserve the result, and just return null, propagating null all the way back up to the root call.

What you should do is something along the lines of:

else {
    HeapNode leftResult = getHeapNodeRec(key, curr.getLeft());
    if (leftResult != null) { 
        return leftResult; 
    }

    HeapNode rightResult = getHeapNodeRec(key, curr.getRight());
    if (rightResult != null) { 
        return rightResult; 
     }
}
Jeeter
  • 5,887
  • 6
  • 44
  • 67
0

You need to return the value that you are recursively fetching, like so.

private HeapNode getHeapNode(double key) {
    //ELEMENT IS NOT AVAILABLE HERE, NULL-Pointer, ALWAYS
    return getHeapNodeRec(key, rootHeapNode);
}

private HeapNode getHeapNodeRec(double key, HeapNode curr) {
    if (curr == null) {
        return null;
    }
    if (curr.getKey() == key) {
        //ELEMENT IS AVAILABLE HERE, I can access its data!
        return curr;
    }
    else {
        if (getHeapNodeRec(key, curr.getLeft()) != null) {
            return curr.getLeft();
        }
        if (getHeapNodeRec(key, current.getRight()) != null) {
            return curr.getRight();
        }
    }
    return null;
}  
Patrick Bell
  • 769
  • 3
  • 15