[英]List vs array as an argument of recursion in java
我有兩種解決方案,如下所示打印從根到所有葉子的所有路徑。
在Sol 1中,使用List作為遞歸中的參數來添加從根到每個葉節點的路徑,然后從遞歸返回后,我必須刪除要返回的節點。 根據我的知識,這是因為List是存儲在堆中並由所有人共享的對象。 因此,每個遞歸調用都使用相同的List對象列表,因此需要刪除。
但是,在Sol 2中,我使用array作為參數,並且不需要像List一樣刪除返回的節點。 我不明白為什么?
根據我的理解,由於數組也是一個對象,存儲在堆中並由每個遞歸調用共享。 因此,假定與List情況相同,並且我認為我需要從遞歸調用中刪除返回的節點。 但這不是真的。
您能解釋一下為什么不必像List一樣刪除從遞歸調用返回的節點嗎? 我對列表大小寫的理解是正確的嗎? 請讓我知道這對我來說很混亂。
Sol 1:遞歸1-使用列表
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:遞歸2-使用數組
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**
}
由於index ++。 在列表中,您總是得到第一個元素。 我的意思是,您總是有1個元素,因為最后將其刪除。 在數組中,由於使用index ++,您總是得到最后一個元素。
因為在數組中,我們只是在下一個函數調用中覆蓋了元素,所以不需要刪除它。
請注意,使用List
進行add
(總是追加到末尾,顯然不會被另一個add
覆蓋,因此我們需要remove
),但是對於數組,我們只是設置index
- th元素(因此,如果該位置已經有一個元素,我們只需覆蓋它)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.