简体   繁体   中英

List vs array as an argument of recursion in java

I have two solutions to print all paths from the root to all leaves in a binary tree as follows.

In Sol 1, used List as an argument in the recursion to add path from the root to each leaf node and then after returning from the recursion, I have to remove a node which is being returned. Based on my knowledge, this is because List is an object stored in heap and shared by everyone. So each recursive call uses the same List object list and thus needs to remove.

However, in Sol 2, I used array as an argument and I don't need to remove the returned node unlike List. I don't understand why?

Based on my understanding, since array is also an object, stored in heap and shared by every recursive call. Thus it was supposed be the same with the List case, and I thought I needed to remove the returned node from the recursive call. But it is not true.

Could you explain why the returned node from the recursive call doesn't have to be removed unlike List? My understand of List case is correct? Please let me know it's confusing for me.

Sol 1: recursive 1 - using List

void printPathsFromRootToLeavesRec1(BTNode node, List<BTNode> list) {
    if(node == null) return;

    list.add(node);
    // viristed and added node from root --> left subtree --> right subtree

    if(node.left == null && node.right == null)
        printNodeList(list);

    printPathsFromRootToLeavesRec1(node.left, list);
    printPathsFromRootToLeavesRec1(node.right, list);

    **// Note 1: KEY POINT = Remove after print !!!
    list.remove(node);**
}

Sol 2: Recursive 2 - using array

void printPathFromRootToLeavsRec2(BTNode node, BTNode[] array, int index) {
    if(node == null) return;

    array[index] = node;  
    index++;

    if(node.left == null && node.right == null) printPathArray(array, index);       
    printPathFromRootToLeavsRec2(node.left,  array, index);
    printPathFromRootToLeavsRec2(node.right, array, index);
            **// We don't need to remove the returned node in the array case unlike List**
}

Because of index++. In a list, you are always getting the first element. I mean, you always have 1 element because you remove it at the end. In the array, because index++, you always get the last one element.

Because, in the array, we just overwrite the element in the next function call, so there's no need to remove it.

Note that with the List we're doing an add (which always appends to the end, which obviously won't be overwritten by doing another add , thus we need a remove ), but with the array we're simply setting the index -th element (so, if there's already an element at that position, we simply overwrite it).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM