0

I have a generic binary tree. What I want to do is find a node, providing an attribute to find that node an then return it. For example, my tree has Objects type X, X has an attribute code, so I have to compare the code of the current node with the code provided.

private X find_X_by_code(Node<X> node, String code) {
    if (!node.element.code().equals(code)){
        if (node.left != null){
            find_X_by_code(node.left,code);
        }
        if (node.right != null){
            find_X_by_code(node.right,code);
        }
    }
    return node.element;
}

I call this method like this:

find_X_by_code(root,code);

For some reason when the codes match, it keeps going on.

JJHH
  • 67
  • 1
  • 9

2 Answers2

0

You might have to tweak a little depending upon your use.

if(node != null){
    if(node.element.code().equals(code)){
       return node.element;
    } else {
        Node tempNode = find_X_by_code(node.left, code);
        if(tempNode == null) {
            tempNode = find_X_by_code(node.right, code);
        }
        return tempNode.element;
     }
} else {
    return null;
}

How to search for a node in a tree and return it?

Community
  • 1
  • 1
Devendra Lattu
  • 2,732
  • 2
  • 18
  • 27
0

You're missing the returns in the recursive calls and a handle for the case when the node isn't present (reach null). Change it to:

private X find_X_by_code(Node<X> node, String code) {
    if (node == null) { return null; }
    if (!node.element.code().equals(code)){
        if (node.left != null){
            return find_X_by_code(node.left,code);
        }
        if (node.right != null){
            return find_X_by_code(node.right,code);
        }
    }
    return node.element;

}

twain249
  • 5,666
  • 1
  • 21
  • 26