-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflatten-binary-tree-to-linked-list.cc
More file actions
39 lines (33 loc) · 1.03 KB
/
flatten-binary-tree-to-linked-list.cc
File metadata and controls
39 lines (33 loc) · 1.03 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
#include <algorithm>
#include <stack>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
TreeNode() : value(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : value(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : value(x), left(left), right(right) {}
int value;
TreeNode *left;
TreeNode *right;
};
class Solution {
public:
void flatten(TreeNode *root) {
if (root == nullptr) return;
flatten(root->left);
flatten(root->right);
TreeNode *temp = root->right;
root->right = root->left;
root->left = nullptr;
while (root->right != nullptr) root = root->right;
root->right = temp;
}
};
inline TreeNode *TN(int x, TreeNode *left = nullptr, TreeNode *right = nullptr) {
return new TreeNode(x, left, right);
}
int main(int argc, char const *argv[]) {
Solution solution;
TreeNode *root = TN(1, TN(2, TN(3), TN(4)), TN(5, nullptr, TN(6)));
solution.flatten(root);
}