-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_114.cpp
More file actions
30 lines (27 loc) · 719 Bytes
/
Copy pathP_114.cpp
File metadata and controls
30 lines (27 loc) · 719 Bytes
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
#include <bits/stdc++.h>
#define fast_io \
ios::sync_with_stdio(false); \
cin.tie(nullptr);
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int _val) { val = _val; }
};
void flatten(TreeNode *root) { dfs(root); }
vector<TreeNode *> dfs(TreeNode *node) {
if (node == nullptr) {
return vector<TreeNode *>(2);
}
vector<TreeNode *> l = dfs(node->left);
vector<TreeNode *> r = dfs(node->right);
node->left = nullptr;
node->right = (TreeNode *)l[0];
if (l[1] != nullptr) {
l[1]->right = (TreeNode *)r[0];
} else {
node->right = (TreeNode *)r[0];
}
return {node, r[1] == nullptr ? l[1] == nullptr ? node : l[1] : r[1]};
}