0430. 扁平化多级双向链表

文章目录

题目链接

https://leetcode.cn/problems/flatten-a-multilevel-doubly-linked-list/

题目描述

将多级双向链表扁平化:把每个节点的 child 子链表插入到该节点与其 next 之间,最终得到单层双向链表,所有 child 置为 null。

推荐写法(返回尾节点,整体 O(n))

java 复制代码
/*
// Definition for a Node.
class Node {
    public int val;
    public Node prev;
    public Node next;
    public Node child;
}
*/
class Solution {
    public Node flatten(Node head) {
        flattenTail(head);
        return head;
    }

    // 扁平化以 head 为首的链表,返回该段扁平化后的尾节点
    private Node flattenTail(Node head) {
        Node cur = head;
        Node last = head; // 记录当前已扁平段的尾

        while (cur != null) {
            Node next = cur.next;
            if (cur.child != null) {
                // 先把 child 段扁平化,得到其尾节点 childTail
                Node childHead = cur.child;
                Node childTail = flattenTail(childHead);

                // 将 child 段插入 cur 与 next 之间
                cur.next = childHead;
                childHead.prev = cur;
                cur.child = null;

                // 接回 next
                if (next != null) {
                    childTail.next = next;
                    next.prev = childTail;
                }

                // 更新 last,并从 childTail 继续
                last = childTail;
                cur = next;
            } else {
                last = cur;
                cur = next;
            }
        }
        return last;
    }
}

复杂度分析

  • 时间复杂度:O(n),每个节点仅被访问和重连常数次。
  • 空间复杂度:O(d),d 为最大嵌套深度(递归栈);可改迭代+显式栈降为 O(h) 显式空间。
相关推荐
Mr Xu_19 小时前
告别硬编码:前端项目中配置驱动的实战优化指南
前端·javascript·数据结构
czxyvX19 小时前
017-AVL树(C++实现)
开发语言·数据结构·c++
数智工坊19 小时前
【数据结构-队列】3.2 队列的顺序-链式实现-双端队列
数据结构
elseif12319 小时前
【C++】并查集&家谱树
开发语言·数据结构·c++·算法·图论
徐小夕@趣谈前端19 小时前
Web文档的“Office时刻“:jitword共建版2.0发布!让浏览器变成本地生产力
前端·数据结构·vue.js·算法·开源·编辑器·es6
Nebula_g20 小时前
线程进阶: 无人机自动防空平台开发教程(更新)
java·开发语言·数据结构·学习·算法·无人机
xuxie9921 小时前
day 23 树
数据结构
EnglishJun1 天前
数据结构的学习(四)---栈和队列
数据结构·学习
数智工坊1 天前
【数据结构-特殊矩阵】3.5 特殊矩阵-压缩存储
数据结构·线性代数·矩阵
芝士爱知识a1 天前
AlphaGBM 深度解析:下一代基于 AI 与蒙特卡洛的智能期权分析平台
数据结构·人工智能·python·股票·alphagbm·ai 驱动的智能期权分析·期权