I was looking at this code in Java to convert a sorted linked list to a balanced BST and I wanted to know why implementation #1 doesn't work. What is the Java reason that when I create a wrapper object and pass it around then it works perfectly but when I use the local reference it doesnt ? The objects are still created on the heap right.
Implementation #1
BinaryTree.Node sortedListToBST(MyList.Node w, int start, int end)
{
if (start > end) return null;
int mid = start + (end - start) / 2;
BinaryTree.Node left = sortedListToBST(w, start, mid-1);
BinaryTree.Node parent = new BinaryTree.Node(w.getVal());
w = w.getNext();
BinaryTree.Node right = sortedListToBST(w, mid+1, end);
parent.left = left;
parent.right =right;
return parent;
}
BinaryTree.Node sortedListToBST(MyList.Node head, int n) {
return sortedListToBST(head, 0, n-1);
}
Implementation #2
BinaryTree.Node sortedListToBSTWrapper(Wrapper w, int start, int end)
{
if (start > end) return null;
int mid = start + (end - start) / 2;
BinaryTree.Node left = sortedListToBSTWrapper(w, start, mid-1);
BinaryTree.Node parent = new BinaryTree.Node(w.node.getVal());
w.node = w.node.getNext();
BinaryTree.Node right = sortedListToBSTWrapper(w, mid+1, end);
parent.left = left;
parent.right =right;
return parent;
}
BinaryTree.Node sortedListToBSTWrapper(MyList.Node head, int n) {
Wrapper w = new Wrapper();
w.node = head;
return sortedListToBSTWrapper(w, 0, n-1);
}