426. Convert a Binary Search Tree to Doubly Linked List

Convert a Binary Search Tree to a sorted Circular Doubly-Linked List in place.

You can think of the left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element.

We want to do the transformation in place. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor. You should return the pointer to the smallest element of the linked list.

 

Example 1:

Input: root = [4,2,5,1,3]

Output: [1,2,3,4,5]

Explanation: The figure below shows the transformed BST. The solid line indicates the successor relationship, while the dashed line means the predecessor 
 1 class Solution {
 2     public Node treeToDoublyList(Node root) {
 3         if (root == null) {
 4             return null;
 5         }
 6 
 7         Node leftHead = treeToDoublyList(root.left);
 8         Node rightHead = treeToDoublyList(root.right);
 9         root.left = root;
10         root.right = root;
11         return connect(connect(leftHead, root), rightHead);
12     }
13 
14     // Used to connect two circular doubly linked lists. n1 is the head of circular DLL as well as n2.
15     private Node connect(Node head1, Node head2) {
16         if (head1 == null) return head2;
17         if (head2 == null) return head1;
18 
19         Node tail1 = head1.left;
20         Node tail2 = head2.left;
21 
22         tail1.right = head2;
23         head2.left = tail1;
24         tail2.right = head1;
25         head1.left = tail2;
26 
27         return head1;
28     }
29 }

 

posted @ 2016-11-11 07:54  北叶青藤  阅读(587)  评论(0)    收藏  举报