[LeetCode] Convert Binary Search Tree to Sorted Doubly Linked List

426. Convert Binary Search Tree to Sorted 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*
// Definition for a Node.
class Node {
public:
int val;
Node* left;
Node* right;

Node() {}

Node(int _val) {
val = _val;
left = NULL;
right = NULL;
}

Node(int _val, Node* _left, Node* _right) {
val = _val;
left = _left;
right = _right;
}
};
*/

class Solution {
map<int, Node*> m;
void explore(Node* n) {
if(!n) return;
m[n->val] = n;
explore(n->left);
explore(n->right);
}
public:
Node* treeToDoublyList(Node* root) {
if(!root) return root;
explore(root);
for(auto i = begin(m); i != end(m); i++) {
Node* n = (i)->second;
if(i == begin(m)) n->left = (prev(end(m)))->second;
else n->left = prev(i)->second;
if(i == prev(end(m))) n->right = (begin(m))->second;
else n->right = next(i)->second;
}
return m.begin()->second;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/29/PS/LeetCode/convert-binary-search-tree-to-sorted-doubly-linked-list/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.