Skip to content

Commit 20ed55b

Browse files
authored
Create convert-binary-search-tree-to-sorted-doubly-linked-list.cpp
1 parent 67fc0bd commit 20ed55b

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Time: O(n)
2+
// Space: O(h)
3+
4+
/*
5+
// Definition for a Node.
6+
class Node {
7+
public:
8+
int val;
9+
Node* left;
10+
Node* right;
11+
12+
Node() {}
13+
14+
Node(int _val, Node* _left, Node* _right) {
15+
val = _val;
16+
left = _left;
17+
right = _right;
18+
}
19+
};
20+
*/
21+
class Solution {
22+
public:
23+
Node* treeToDoublyList(Node* root) {
24+
if (!root) {
25+
return nullptr;
26+
}
27+
Node *left_head = root, *left_tail = root;
28+
Node *right_head = root, *right_tail = root;
29+
if (root->left) {
30+
left_head = treeToDoublyList(root->left);
31+
left_tail = left_head->left;
32+
}
33+
if (root->right) {
34+
right_head = treeToDoublyList(root->right);
35+
right_tail = right_head->left;
36+
}
37+
left_tail->right = root, right_head->left = root;
38+
root->left = left_tail, root->right = right_head;
39+
left_head->left = right_tail, right_tail->right = left_head;
40+
return left_head;
41+
}
42+
};

0 commit comments

Comments
 (0)