Search code examples
javabinary-treepreorder

Exit binary pre order traversal before completion


I have a binary tree consisting of various nodes. I want to traverse the tree using pre order recursion, find a node with a matching description (desc) and return it if it exists. The traversal continues to completion however. Is there a logical mistake i am making, or is the traversal algorithm not suitable?

Here is the pre order traversal recusion function and where I call it below:

public Node replaceNodes(Node currentNode, int itemId, String desc) {

if (currentNode == null) {
    System.out.println("null");
}

if (currentNode != null) {
    //System.out.println(desc + " " + currentNode.getDesc());
    if (currentNode.getDesc().matches(desc) 
            && currentNode.getKey() != itemId) {
        System.out.println("returned");
        return currentNode;
        //System.out.println(currentNode.getDesc());
    } else {
        replaceNodes(currentNode.leftChild, itemId, desc);
        replaceNodes(currentNode.rightChild, itemId, desc);
        //System.out.println("replace");
    }
} 

return null;
}


  Node replaceItem = r1Items.replaceNodes(r1Items.
                            getRoot(), searchId, searchNode.getDesc());
                    //check suitable item found

Thanks. I am happy to clarify further if needed.


Solution

  • You call your method recursively but you are not storing the value returned from the recursive call. Currently, you will get the correct result only if the node you are looking for is the root node.

    I think you'd want something like the following in the else statement.

    . . . 
    } else {
       Node left = replaceNodes(currentNode.leftChild, itemId, desc);
       if(left != null) { return left; }
       Node right = replaceNodes(currentNode.rightChild, itemId, desc);
       if(right != null) { return right; }
    }
    . . . 
    

    The following is a little simplified

    . . . 
    } else {
       Node left = replaceNodes(currentNode.leftChild, itemId, desc);
       if(left != null) { return left; }
       return replaceNodes(currentNode.rightChild, itemId, desc);
    }
    . . .