-
Notifications
You must be signed in to change notification settings - Fork 262
Expand file tree
/
Copy pathconvert-binary-search-tree-to-doubly-linked-list.cpp
More file actions
53 lines (51 loc) · 1.21 KB
/
convert-binary-search-tree-to-doubly-linked-list.cpp
File metadata and controls
53 lines (51 loc) · 1.21 KB
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
47
48
49
50
51
52
53
// Time: O(n)
// Space: O(h)
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
* Definition of Doubly-ListNode
* class DoublyListNode {
* public:
* int val;
* DoublyListNode *next, *prev;
* DoublyListNode(int val) {
* this->val = val;
this->prev = this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of tree
* @return: the head of doubly list node
*/
DoublyListNode* bstToDoublyList(TreeNode* root) {
DoublyListNode *prev = nullptr, *head = nullptr;
treeToDoublyList(root, &prev, &head);
return head;
}
void treeToDoublyList(TreeNode *p, DoublyListNode **prev, DoublyListNode **head) {
if (!p) {
return;
}
treeToDoublyList(p->left, prev, head);
DoublyListNode *root = new DoublyListNode(p->val);
if (!*prev) {
*head = root;
} else {
root->prev = *prev;
(*prev)->next = root;
}
*prev = root;
treeToDoublyList(p->right, prev, head);
}
};