java - 在这个“扁平化双向链表”代码中,递归是如何工作的?
问题描述
问题来自 leetcode #430 Flatten a Multilevel 双链表。所以基本上,每个节点都有三个字段:next、prev 和 child。问题要求展平给定的链表。
public Node flatten(Node head) {
flattenHelper(head);
return head;
}
public Node flattenHelper(Node head){
if(head.next == null){
//return if reach the tail
System.out.println("returned " + head.val);
return head;
}
if(head.child != null){
Node prevNext = head.next;
//link current node's next field to its child
head.next = head.child;
head.child = null;
head.next.prev = head;
//the tail of the child linked-list
Node children = flatten(head.next);
children.next = prevNext;
prevNext.prev = children;
}
Node x = flatten(head.next);
System.out.println("current Node value: " + head.val + " returned from the bottom: " + x.val);
return x;
}
我知道有更好的方法来解决这个问题,但为什么这段代码不起作用?
根据我对递归的理解,最底层堆栈的返回值应该通过 传递给它的调用者堆栈Node x = flatten(head.next); return x;
,并最终到达Node children = flatten(head.next);
连接。
但是,在堆栈向上的过程中,Node x = flatten(head.next); return x;
返回当前节点下一个堆栈的节点,而不是从最底部堆栈返回的节点。
非常感谢您的帮助!
解决方案
推荐阅读
- javascript - 自定义多选下拉元素中的 checkedChange 事件
- jasper-reports - Jasper 报告在表格中添加静态文本行
- r - 如何将根据变量值着色的点添加到地图?
- ios - 如何在 Swift 中处理竞争条件读/写问题?
- python - 加快雅虎财经的网页抓取速度
- javascript - Ajax call to ColdFusion component not returning data
- c# - Moq 单元测试用例 - 带有 WebAPI 的 ASP.NET MVC
- javascript - 发生错误时 React-create-app 无法打开 IDE
- python - 用 python turtle 重复函数
- java - 如何将声音/音乐放入我的 Java 项目