摘要:
Problem
You are given a doubly linked list which in addition to the next and previous pointers, it could have a child pointer, which may or may not point to a separate doubly linked list. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure, as shown in the example below.
Flatten the list so that all the nodes appear in a single-level, doubly linked list. You are given the head of the first level of the list.
Example:
Input: 1---2---3---4---5---6--NULL | 7---8---9---10--NULL | 11--12--NULL Output: 1-2-3-7-8-11-12-9-10-4-5-6-NULL
Note:
/* // Definition for a Node. class Node { public int val; public Node prev; public Node next; public Node child; public Node() {} public Node(int _val,Node _prev,Node _next,Node _child) { val = _val; prev = _prev; next = _next; child = _child; } }; */Solution - Recursive
class Solution { public Node flatten(Node head) { Node dummy = head; while (head != null) { Node next = head.next; if (head.child != null) { Node child = flatten(head.child); head.child = null; head.next = child; child.prev = head; while (head.next != null) head = head.next; } if (next != null) { head.next = next; next.prev = head; } head = head.next; } return dummy; } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/72409.html
摘要:步骤如下代码如下思路二循环上面的思路同样可以通过循环的方式来解决。基本步骤如下代码如下思路减少遍历次数之前的两种思路,都会出现大量的重复遍历,重复遍历和叶子节点的深度成正相关,可以想方法将重复遍历的次数减少。 题目要求 You are given a doubly linked list which in addition to the next and previous pointe...
摘要:您将获得一个双向链表,除了下一个和前一个指针之外,它还有一个子指针,可能指向单独的双向链表。扁平化列表,使所有结点出现在单级双链表中。 您将获得一个双向链表,除了下一个和前一个指针之外,它还有一个子指针,可能指向单独的双向链表。这些子列表可能有一个或多个自己的子项,依此类推,生成多级数据结构,如下面的示例所示。 扁平化列表,使所有结点出现在单级双链表中。您将获得列表第一级的头部。 Yo...
摘要:您将获得一个双向链表,除了下一个和前一个指针之外,它还有一个子指针,可能指向单独的双向链表。扁平化列表,使所有结点出现在单级双链表中。 您将获得一个双向链表,除了下一个和前一个指针之外,它还有一个子指针,可能指向单独的双向链表。这些子列表可能有一个或多个自己的子项,依此类推,生成多级数据结构,如下面的示例所示。 扁平化列表,使所有结点出现在单级双链表中。您将获得列表第一级的头部。 Yo...
Problem Convert a BST to a sorted circular doubly-linked list in-place. Think of the left and right pointers as synonymous to the previous and next pointers in a doubly-linked list. Lets take the foll...
Problem Flatten a binary tree to a fake linked list in pre-order traversal.Here we use the right pointer in TreeNode as the next pointer in ListNode. Example 1 1 ...
阅读 2945·2021-11-22 15:25
阅读 2239·2021-11-18 10:07
阅读 1044·2019-08-29 15:29
阅读 471·2019-08-29 13:25
阅读 1502·2019-08-29 12:58
阅读 3200·2019-08-29 12:55
阅读 2910·2019-08-29 12:28
阅读 499·2019-08-29 12:16