forked from Astha369/CPP_Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflatteningbinarytree.cpp
46 lines (44 loc) · 1.07 KB
/
flatteningbinarytree.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
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void flatten(TreeNode* root) {
if (!root) {
return;
}
TreeNode* rightSubtree = root->right;
flatten(root->left);
root->right = root->left;
root->left = NULL;
TreeNode* current = root;
while (current->right) {
current = current->right;
}
current->right = rightSubtree;
flatten(rightSubtree);
}
void printFlattenedTree(TreeNode* root) {
while (root) {
cout << root->val << " ";
root = root->right;
}
cout << endl;
}
int main() {
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->left->left = new TreeNode(3);
root->left->right = new TreeNode(4);
root->right = new TreeNode(5);
root->right->right = new TreeNode(6);
cout << "Original Tree:" << endl;
printFlattenedTree(root);
flatten(root);
cout << "Flattened Tree:" << endl;
printFlattenedTree(root);
return 0;
}