java—递归在这个“扁平双链表”代码中是如何工作的?

liwlm1x9  于 2021-06-30  发布在  Java
关注(0)|答案(0)|浏览(180)

问题来自leetcode#430展平多级双链表。所以基本上,每个节点都有三个字段: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; 返回当前节点下一个堆栈的节点,而不是从最底层堆栈返回的节点。
示例测试用例
系统输出打印
非常感谢你的帮助!

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题