430. Flatten a Multilevel Doubly Linked List

Doubly linked list:

public class Solution {

    Node last = null;

    public Node Flatten(Node head) {

        if (head == null) return null;

        SetNext(head);

        return head;

    }

    

    private void SetNext(Node head)

    {

        Node next = head.next;

        last = head;

        if (head.child != null)

        {

            SetNext(head.child);

            head.next = head.child;

            head.next.prev = head;

            head.child = null; 

        }

        

        if (next != null)

        {

            last.next = next;

            next.prev = last;

            SetNext(next);

        }

    }

}

留言