I'm currently studying Cracking the Coding interview, and I believe my basic understanding of pointers are being called into question. I am currently looking at a solution to make a linked list for every level of a binary tree. The solution is as follows:
void createLevelLinkedList(TreeNode root, ArrayList<LinkedList<TreeNode» lists, int level) {
if (root == null) return; // base case
LinkedList<TreeNode> list = null;
if (lists.size() == level) { // Level not contained in list
list = new LinkedList<TreeNode>();
/* Levels are always traversed in order. So., if this is the
* first time we've visited level i, we must have seen levels
* 0 through i - 1. We can therefore safely add the level at
* the end. */
lists.add(list);
} else {
list = lists.get(level);
}
list.add(root);
createLevelLinkedList(root.left, lists, level + 1);
createLevelLinkedList(root.right, lists, level + 1);
}
ArrayList<LinkedList<TreeNode» createLevelLinkedList(TreeNode root) {
ArrayList<LinkedList<TreeNode» lists = new ArrayList<LinkedList<TreeNode»();
createLevelLinkedList(root, lists, 0);
return lists;
}
This solution greatly confuses me, because in the createLeveLinkedList function with only the root parameter (the driver function), a new list of linked lists is created. From a java perspective, if it is passed by value, after createLevelLinkedLists(root, lists, 0) is called, to my understanding, lists should not have changed.
If it was C++, I could understand it if they passed the pointer of the lists object into the function.
Could someone please clarify this?
Apologies for the formatting, I'm still not sure how it works on stackoverflow.
Thanks