-
Notifications
You must be signed in to change notification settings - Fork 3
/
426.cpp
47 lines (41 loc) · 892 Bytes
/
426.cpp
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
/*
// 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 {
public:
Node* first = nullptr;
Node* last = nullptr;
void dfs(Node* node) {
if (node == nullptr) return;
if (node->left) dfs(node->left);
if (!first) first = node;
node->left = last;
if (last) last->right = node;
last = node;
if (node->right) dfs(node->right);
}
Node* treeToDoublyList(Node* root) {
if (root == nullptr) return nullptr;
dfs(root);
first->left = last;
last->right = first;
return first;
}
};