[英]How does this recursion and back tracking work in LeetCode?
This function which will print the nodes of a linked list in reverse:这个 function 将反向打印链表的节点:
void recur(ListNode head) {
if(head == null) return;
recur(head.next);
tmp.add(head.val);
}
If the list is 1 -> 2 -> 3 then tmp
(an ArrayList
) will add the value of the node.如果列表是1 -> 2 -> 3则
tmp
(一个ArrayList
)将添加节点的值。
At last, we can get a list [3, 2, 1]
via printing tmp
.最后,我们可以通过打印
tmp
得到一个列表[3, 2, 1]
。 However, I do not know why it works.但是,我不知道它为什么起作用。 Why does the
recur
function loop to the last node then add the values in reverse order?为什么递归
recur
循环到最后一个节点然后以相反的顺序添加值?
It's pretty much simple, let's consider the [1 -> 2]
node with two ListNode and we want to reverse with you function:这非常简单,让我们考虑具有两个 ListNode 的
[1 -> 2]
节点,我们想与您反转 function:
void recur(ListNode head) {
if (head == null) return;
recur(head.next);
tmp.add(head.val);
}
1
value, this check if (head == null)
will return false
since head node is not null.1
值,此检查if (head == null)
将返回false
,因为 head 节点不是 null。recur
but for the next node with value 2
, and execution of recur
start over but with node 2
as a head node.recur
但对于值为2
的下一个节点,并且recur
的执行重新开始,但节点2
作为头节点。 We again check if (head == null)
-> false
, same reason, head is not null here.if (head == null)
-> false
,同样的原因,这里的 head 不是 null。recur
but for the next node which is null head.next -> null
, since there are no nodes anymore after node 2
.recur
但对于下一个节点 null head.next -> null
,因为在节点2
之后不再有节点。 We check if (head == null)
, but now we have true
, the current node, meaning there are no nodes left after and we can't go further calling recur()
again.if (head == null)
,但现在我们有了true
,即当前节点,这意味着之后没有节点,我们不能 go 进一步调用recur()
。 So, we stop the recursion with a return
statement.return
语句停止递归。recur(head.next)
ends by return
statement.recur(head.next)
的执行以return
语句结束。 That means, this node is the last one, and we put its value to the tmp
.tmp
中。 And the execution of recur
for ListNode 2
ends, since there are no code lines after.2
的recur
执行结束,因为后面没有代码行。recur
for node 2
ends its execution we proceed and put value 1
to tmp
array.2
的recur
结束了它的执行,我们继续并将值1
放入tmp
数组。 if (head == null) return;
- this check, called recursion base case
, meaning when we need to end execution and exit?
- 这个检查,称为递归
base case
,意味着when we need to end execution and exit?
, without it recursion will go infinitely. ,没有它递归将无限次 go。
We dig to the end of the ListNode and then return again to the top.我们挖掘到 ListNode 的末尾,然后再次返回顶部。 To be able to put ListNode value to the
tmp
we need first put next value to the tmp
and so on.为了能够将 ListNode 值放入
tmp
,我们首先需要将下一个值放入tmp
,依此类推。
I hope, I explained more accurately and its more clear for you now.我希望,我现在解释得更准确,更清楚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.