I have this function to find all the paths from root to leaf in a BST.
public static void paths(Node node, LinkedList<Integer> list) {
if (node == null) {
return;
}
list.add(node.data);
if (node.left == null && node.right == null) {
print(list);
return;
} else {
paths(node.left, list);
paths(node.right, list);
}
}
public static void print(LinkedList<Integer> list1) {
System.out.println("Contents of list: " + list1);
}
I call it using:
LinkedList list = new LinkedList();
paths(bt.root, list);
e.g:
07
02
01 05
It prints:
7 2 1
7 2 1 5 [instead of 7 2 5]
Somehow the value 1 is retained in the “list” even after it returns from the recursion.
As others have said, there’s only a single
LinkedListobject in use here. xyz incorrectly described this as using pass by reference, but it’s actually passing the value oflistwhich is a reference, by value. (Changes to the parameter itself, such as assigning it a different value, aren’t visible to the caller; changes within the object that the parameter refers to are visible.)It’s really important that you understand how variables, objects and references work in Java. When you write (say):
… then the value of
nodeis not aNodeobject. It’s a reference to aNodeobject. Assignment and parameter passing deal with that value (the reference) not the object. So for example:node1andnode2now refer to the same object – there’s no object copying involved.As for how you can fix this, there are two options that spring to mind:
ncompletes, the linked list is back to havingn-1elements.You can do this by simply adding a call to:
either in both branches, or in a finally block, or removing the explicit
return: