摘要:
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; } }
文章版權歸作者所有,未經(jīng)允許請勿轉載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉載請注明本文地址:http://systransis.cn/yun/72409.html
摘要:步驟如下代碼如下思路二循環(huán)上面的思路同樣可以通過循環(huán)的方式來解決?;静襟E如下代碼如下思路減少遍歷次數(shù)之前的兩種思路,都會出現(xiàn)大量的重復遍歷,重復遍歷和葉子節(jié)點的深度成正相關,可以想方法將重復遍歷的次數(shù)減少。 題目要求 You are given a doubly linked list which in addition to the next and previous pointe...
摘要:您將獲得一個雙向鏈表,除了下一個和前一個指針之外,它還有一個子指針,可能指向單獨的雙向鏈表。扁平化列表,使所有結點出現(xiàn)在單級雙鏈表中。 您將獲得一個雙向鏈表,除了下一個和前一個指針之外,它還有一個子指針,可能指向單獨的雙向鏈表。這些子列表可能有一個或多個自己的子項,依此類推,生成多級數(shù)據(jù)結構,如下面的示例所示。 扁平化列表,使所有結點出現(xiàn)在單級雙鏈表中。您將獲得列表第一級的頭部。 Yo...
摘要:您將獲得一個雙向鏈表,除了下一個和前一個指針之外,它還有一個子指針,可能指向單獨的雙向鏈表。扁平化列表,使所有結點出現(xiàn)在單級雙鏈表中。 您將獲得一個雙向鏈表,除了下一個和前一個指針之外,它還有一個子指針,可能指向單獨的雙向鏈表。這些子列表可能有一個或多個自己的子項,依此類推,生成多級數(shù)據(jù)結構,如下面的示例所示。 扁平化列表,使所有結點出現(xiàn)在單級雙鏈表中。您將獲得列表第一級的頭部。 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 ...
閱讀 2970·2021-11-22 15:25
閱讀 2251·2021-11-18 10:07
閱讀 1057·2019-08-29 15:29
閱讀 483·2019-08-29 13:25
閱讀 1515·2019-08-29 12:58
閱讀 3211·2019-08-29 12:55
閱讀 2923·2019-08-29 12:28
閱讀 514·2019-08-29 12:16