Flatten a Multilevel Doubly Linked List
<p>You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional <strong>child pointer</strong>. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a <strong>multilevel data structure</strong> as shown in the example below.</p>

<p>Given the <code>head</code> of the first level of the list, <strong>flatten</strong> the list so that all the nodes appear in a single-level, doubly linked list. Let <code>curr</code> be a node with a child list. The nodes in the child list should appear <strong>after</strong> <code>curr</code> and <strong>before</strong> <code>curr.next</code> in the flattened list.</p>

<p>Return <em>the </em><code>head</code><em> of the flattened list. The nodes in the list must have <strong>all</strong> of their child pointers set to </em><code>null</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/11/09/flatten11.jpg" style="width: 700px; height: 339px;" />
<pre>
<strong>Input:</strong> head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
<strong>Output:</strong> [1,2,3,7,8,11,12,9,10,4,5,6]
<strong>Explanation:</strong> The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:
<img src="https://assets.leetcode.com/uploads/2021/11/09/flatten12.jpg" style="width: 1000px; height: 69px;" />
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/11/09/flatten2.1jpg" style="width: 200px; height: 200px;" />
<pre>
<strong>Input:</strong> head = [1,2,null,3]
<strong>Output:</strong> [1,3,2]
<strong>Explanation:</strong> The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:
<img src="https://assets.leetcode.com/uploads/2021/11/24/list.jpg" style="width: 300px; height: 87px;" />
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> head = []
<strong>Output:</strong> []
<strong>Explanation:</strong> There could be empty list in the input.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li>The number of Nodes will not exceed <code>1000</code>.</li>
	<li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li>
</ul>

<p>&nbsp;</p>
<p><strong>How the multilevel linked list is represented in test cases:</strong></p>

<p>We use the multilevel linked list from <strong>Example 1</strong> above:</p>

<pre>
 1---2---3---4---5---6--NULL
         |
         7---8---9---10--NULL
             |
             11--12--NULL</pre>

<p>The serialization of each level is as follows:</p>

<pre>
[1,2,3,4,5,6,null]
[7,8,9,10,null]
[11,12,null]
</pre>

<p>To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:</p>

<pre>
[1,    2,    3, 4, 5, 6, null]
             |
[null, null, 7,    8, 9, 10, null]
                   |
[            null, 11, 12, null]
</pre>

<p>Merging the serialization of each level and removing trailing nulls we obtain:</p>

<pre>
[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
</pre>

['flatten-binary-tree-to-linked-list', 'correct-a-binary-tree']
[]
[{"value": "cpp", "text": "C++", "defaultCode": "/*\n// Definition for a Node.\nclass Node {\npublic:\n    int val;\n    Node* prev;\n    Node* next;\n    Node* child;\n};\n*/\n\nclass Solution {\npublic:\n    Node* flatten(Node* head) {\n        \n    }\n};"}, {"value": "java", "text": "Java", "defaultCode": "/*\n// Definition for a Node.\nclass Node {\n    public int val;\n    public Node prev;\n    public Node next;\n    public Node child;\n};\n*/\n\nclass Solution {\n    public Node flatten(Node head) {\n        \n    }\n}"}, {"value": "python", "text": "Python", "defaultCode": "\"\"\"\n# Definition for a Node.\nclass Node(object):\n    def __init__(self, val, prev, next, child):\n        self.val = val\n        self.prev = prev\n        self.next = next\n        self.child = child\n\"\"\"\n\nclass Solution(object):\n    def flatten(self, head):\n        \"\"\"\n        :type head: Node\n        :rtype: Node\n        \"\"\"\n        "}, {"value": "python3", "text": "Python3", "defaultCode": "\"\"\"\n# Definition for a Node.\nclass Node:\n    def __init__(self, val, prev, next, child):\n        self.val = val\n        self.prev = prev\n        self.next = next\n        self.child = child\n\"\"\"\n\nclass Solution:\n    def flatten(self, head: 'Optional[Node]') -> 'Optional[Node]':\n        "}, {"value": "csharp", "text": "C#", "defaultCode": "/*\n// Definition for a Node.\npublic class Node {\n    public int val;\n    public Node prev;\n    public Node next;\n    public Node child;\n}\n*/\n\npublic class Solution {\n    public Node Flatten(Node head) {\n        \n    }\n}"}, {"value": "javascript", "text": "JavaScript", "defaultCode": "/**\n * // Definition for a _Node.\n * function _Node(val,prev,next,child) {\n *    this.val = val;\n *    this.prev = prev;\n *    this.next = next;\n *    this.child = child;\n * };\n */\n\n/**\n * @param {_Node} head\n * @return {_Node}\n */\nvar flatten = function(head) {\n    \n};"}, {"value": "typescript", "text": "TypeScript", "defaultCode": "/**\n * Definition for _Node.\n * class _Node {\n *     val: number\n *     prev: _Node | null\n *     next: _Node | null\n *     child: _Node | null\n *     \n *     constructor(val?: number, prev? : _Node, next? : _Node, child? : _Node) {\n *         this.val = (val===undefined ? 0 : val);\n *         this.prev = (prev===undefined ? null : prev);\n *         this.next = (next===undefined ? null : next);\n *         this.child = (child===undefined ? null : child);\n *     }\n * }\n */\n\n\nfunction flatten(head: _Node | null): _Node | null {\n\n};"}, {"value": "php", "text": "PHP", "defaultCode": "/**\n * Definition for a Node.\n * class Node {\n *     public $val = null;\n *     public $prev = null;\n *     public $next = null;\n *     public $child = null;\n *     function __construct($val = 0) {\n *         $this->val = $val;\n *         $this->prev = null;\n *         $this->next = null;\n *         $this->child = null;\n *     }\n * }\n */\n\nclass Solution {\n    /**\n     * @param Node $head\n     * @return Node\n     */\n    function flatten($head) {\n        \n    }\n}"}, {"value": "swift", "text": "Swift", "defaultCode": "/**\n * Definition for a Node.\n * public class Node {\n *     public var val: Int\n *     public var prev: Node?\n *     public var next: Node?\n *     public var child: Node?\n *     public init(_ val: Int) {\n *         self.val = val\n *         self.prev = nil\n *         self.next = nil\n *         self.child  = nil\n *     }\n * }\n */\n\nclass Solution {\n    func flatten(_ head: Node?) -> Node? {\n        \n    }\n}"}, {"value": "kotlin", "text": "Kotlin", "defaultCode": "/**\n * Definition for a Node.\n * class Node(var `val`: Int) {\n *     var prev: Node? = null\n *     var next: Node? = null\n *     var child: Node? = null\n * }\n */\n\nclass Solution {\n    fun flatten(root: Node?): Node? {\n        \n    }\n}"}, {"value": "golang", "text": "Go", "defaultCode": "/**\n * Definition for a Node.\n * type Node struct {\n *     Val int\n *     Prev *Node\n *     Next *Node\n *     Child *Node\n * }\n */\n\nfunc flatten(root *Node) *Node {\n    \n}"}, {"value": "ruby", "text": "Ruby", "defaultCode": "# Definition for a Node.\n# class Node\n#     attr_accessor :val, :prev, :next, :child\n#     def initialize(val=nil, prev=nil, next_=nil, child=nil)\n#         @val = val\n#         @prev = prev\n#         @next = next_\n#         @child = child\n#     end\n# end\n\n# @param {Node} root\n# @return {Node}\ndef flatten(root)\n    \nend"}, {"value": "scala", "text": "Scala", "defaultCode": "/**\n * Definition for a Node.\n * class Node(var _value: Int) {\n *   var value: Int = _value\n *   var prev: Node = null\n *   var next: Node = null\n *   var child: Node = null\n * }\n */\n\nobject Solution {\n    def flatten(head: Node): Node = {\n    \t\n    }\n}"}]
{
  "name": "flatten",
  "params": [
    {
      "name": "head",
      "type": "ListNode"
    }
  ],
  "return": {
    "type": "ListNode"
  },
  "languages": [
    "cpp",
    "java",
    "python",
    "csharp",
    "javascript",
    "python3",
    "kotlin",
    "ruby",
    "scala",
    "golang",
    "swift",
    "php",
    "typescript"
  ],
  "manual": true, "typescriptCustomType" : "class _Node {\n    val: number\n    prev: _Node | null\n    next: _Node | null\n    child: _Node | null\n    \n    constructor(val?: number, prev? : _Node, next? : _Node, child? : _Node) {\n        this.val = (val===undefined ? 0 : val);\n        this.prev = (prev===undefined ? null : prev);\n        this.next = (next===undefined ? null : next);\n        this.child = (child===undefined ? null : child);\n    }\n}\n"

}
{"cpp": ["C++", "<p>Compiled with <code> clang 19 </code> using the latest C++ 23 standard, and <code>libstdc++</code> provided by GCC 14.</p>\r\n\r\n<p>Your code is compiled with level two optimization (<code>-O2</code>). <a href=\"https://github.com/google/sanitizers/wiki/AddressSanitizer\" target=\"_blank\">AddressSanitizer</a> is also enabled to help detect out-of-bounds and use-after-free bugs.</p>\r\n\r\n<p>Most standard library headers are already included automatically for your convenience.</p>"], "java": ["Java", "<p><code>OpenJDK 21</code>. Using compile arguments: <code>--enable-preview --release 21</code></p>\r\n\r\n<p>Most standard library headers are already included automatically for your convenience.</p>\r\n<p>Includes <code>Pair</code> class from https://docs.oracle.com/javase/8/javafx/api/javafx/util/Pair.html.</p>"], "python": ["Python", "<p><code>Python 2.7.18</code>.</p>\r\n\r\n<p>Most libraries are already imported automatically for your convenience, such as <a href=\"https://docs.python.org/2/library/array.html\" target=\"_blank\">array</a>, <a href=\"https://docs.python.org/2/library/bisect.html\" target=\"_blank\">bisect</a>, <a href=\"https://docs.python.org/2/library/collections.html\" target=\"_blank\">collections</a>. If you need more libraries, you can import it yourself.</p>\r\n\r\n<p>For Map/TreeMap data structure, you may use <a href=\"http://www.grantjenks.com/docs/sortedcontainers/\" target=\"_blank\">sortedcontainers</a> library.</p>\r\n\r\n<p>Note that Python 2.7 <a href=\"https://www.python.org/dev/peps/pep-0373/\" target=\"_blank\">is not maintained anymore</a>. For the latest Python, please choose Python3 instead.</p>"], "csharp": ["C#", "<p><a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-13\" target=\"_blank\">C# 13</a> with .NET 9 runtime</p>"], "javascript": ["JavaScript", "<p><code>Node.js 22.14.0</code>.</p>\r\n\r\n<p>Your code is run with <code>--harmony</code> flag, enabling <a href=\"http://node.green/\" target=\"_blank\">new ES6 features</a>.</p>\r\n\r\n<p><a href=\"https://lodash.com\" target=\"_blank\">lodash.js</a> library is included by default.</p>\r\n\r\n<p>For Priority Queue / Queue data structures, you may use 6.3.2 version of <a href=\"https://github.com/datastructures-js/priority-queue/tree/v6.3.2\" target=\"_blank\">datastructures-js/priority-queue</a> and 4.2.3 version of <a href=\"https://github.com/datastructures-js/queue/tree/v4.2.3\" target=\"_blank\">datastructures-js/queue</a> and 1.0.4 version of <a href=\"https://github.com/datastructures-js/deque/tree/v1.0.4\" target=\"_blank\">datastructures-js/deque</a>.</p>"], "ruby": ["Ruby", "<p><code>Ruby 3.2</code></p>\r\n\r\n<p>Some common data structure implementations are provided in the Algorithms module: https://www.rubydoc.info/github/kanwei/algorithms/Algorithms</p>"], "swift": ["Swift", "<p><code>Swift 6.0</code>.</p>\r\n\r\n<p>You may use the following packages:<br/>\r\n<a href=\"https://github.com/apple/swift-algorithms/tree/1.2.0\" target=\"_blank\">swift-algorithms 1.2.0</a><br/>\r\n<a href=\"https://github.com/apple/swift-collections/tree/1.1.4\" target=\"_blank\">swift-collections 1.1.4</a><br/>\r\n<a href=\"https://github.com/apple/swift-numerics/tree/1.0.2\" target=\"_blank\">swift-numerics 1.0.2</a></p>"], "golang": ["Go", "<p><code>Go 1.23</code></p>\r\n<p>Support <a href=\"https://pkg.go.dev/github.com/emirpasic/gods@v1.18.1\" target=\"_blank\">https://pkg.go.dev/github.com/emirpasic/gods@v1.18.1</a> and <a href=\"https://pkg.go.dev/github.com/emirpasic/gods/v2@v2.0.0-alpha\" target=\"_blank\">https://pkg.go.dev/github.com/emirpasic/gods/v2@v2.0.0-alpha</a> library.</p>"], "python3": ["Python3", "<p><code>Python 3.11</code>.</p>\r\n\r\n<p>Most libraries are already imported automatically for your convenience, such as <a href=\"https://docs.python.org/3/library/array.html\" target=\"_blank\">array</a>, <a href=\"https://docs.python.org/3/library/bisect.html\" target=\"_blank\">bisect</a>, <a href=\"https://docs.python.org/3/library/collections.html\" target=\"_blank\">collections</a>. If you need more libraries, you can import it yourself.</p>\r\n\r\n<p>For Map/TreeMap data structure, you may use <a href=\"http://www.grantjenks.com/docs/sortedcontainers/\" target=\"_blank\">sortedcontainers</a> library.</p>"], "scala": ["Scala", "<p><code>Scala 3.3.1</code>.</p>"], "kotlin": ["Kotlin", "<p><code>Kotlin 2.1.10</code>.</p>"], "php": ["PHP", "<p><code>PHP 8.2</code>.</p>\r\n<p>With bcmath module</p>"], "typescript": ["Typescript", "<p><code>TypeScript 5.7.3, Node.js 22.14.0</code>.</p>\r\n\r\n<p>Compile Options: <code>--alwaysStrict --strictBindCallApply --strictFunctionTypes --target ES2024</code></p>\r\n\r\n<p><a href=\"https://lodash.com\" target=\"_blank\">lodash.js</a> library is included by default.</p>\r\n\r\n<p>For Priority Queue / Queue data structures, you may use 6.3.2 version of <a href=\"https://github.com/datastructures-js/priority-queue/tree/v6.3.2\" target=\"_blank\">datastructures-js/priority-queue</a> and 4.2.3 version of <a href=\"https://github.com/datastructures-js/queue/tree/v4.2.3\" target=\"_blank\">datastructures-js/queue</a> and 1.0.4 version of <a href=\"https://github.com/datastructures-js/deque/tree/v1.0.4\" target=\"_blank\">datastructures-js/deque</a>.</p>"]}
['Linked List', 'Depth-First Search', 'Doubly-Linked List']