LeetCode430-扁平化多级双向链表

思路:用dfs实现扁平化当前节点的child,并返回扁平化的最后一个节点childLast。如果next不为空,则将next链接在childLast后面。
代码:
class Solution {
    public Node flatten(Node head) {
        dfs(head);
        return head;
    }

    //dfs用于扁平化当前节点作为head的链表,并返回扁平化后的最后一个节点
    public Node dfs(Node head){
        Node cur = head;

        //保存最后一个节点,last用于保存child的最后一个节点,便于与next链接
        Node last = null;
        while (cur != null){
            //用于保存当前的cur.next。当进入递归,会改变next的指向
            Node next = cur.next;

            if(cur.child != null){
                Node childLast = dfs(cur.child);

                //先保存cur的next
                next = cur.next;

                //将cur与child相连
                cur.next = cur.child;
                cur.child.prev = cur;

                //将childLast 与next相连
                if(next != null){
                    childLast.next = next;
                    next.prev = childLast;
                }
                //将child置为空
                cur.child = null;
                last = childLast;
            }else {
                last = cur;
            }
            cur = next;
        }
        return last;
    }
}
复杂度分析:时间o(n),n为链表元素个数。空间为0(d),d为链表深度,最坏为o(nb),即前n-1个节点next均为null,只有child
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值