-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathCS_51_FlattenBSTToASortedList.cpp
113 lines (87 loc) · 2.11 KB
/
CS_51_FlattenBSTToASortedList.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <bits/stdc++.h>
using namespace std;
template <typename T>
class TreeNode
{
public:
T data;
TreeNode<T> *left;
TreeNode<T> *right;
TreeNode(T data)
{
this->data = data;
left = NULL;
right = NULL;
}
~TreeNode()
{
if (left)
delete left;
if (right)
delete right;
}
};
/*
Time Complexity : O(N)
Space Complexity : O(N)
Where 'N' is the total number of nodes in the given BST.
*/
void inorder(TreeNode<int> *root, vector<int> &inorderArray)
{
if (root == NULL)
{
return;
}
// Recur for left sub-tree
inorder(root->left, inorderArray);
// Add current node data to array
inorderArray.push_back(root->data);
// Recur for right sub-tree
inorder(root->right, inorderArray);
}
TreeNode<int> *flatten(TreeNode<int> *root)
{
if (root == NULL)
{
return root;
}
// Array to store inorder traversal
vector<int> inorderArray;
inorder(root, inorderArray);
// Create a pointer called newRoot, and store the first value of the array in it.
TreeNode<int> *newRoot = new TreeNode<int>(inorderArray[0]);
// Create a pointer called curr and store the newRoot in it.
TreeNode<int> *curr = newRoot;
for (int i = 1; i < inorderArray.size(); i++)
{
// Create a new node.
TreeNode<int> *temp = new TreeNode<int>(inorderArray[i]);
// Make the left child of curr as NULL and right child as the temp. And make curr = temp.
curr->left = NULL;
curr->right = temp;
curr = temp;
}
// Make both the left and the right child of the last node as NULL.
curr->left = NULL;
curr->right = NULL;
return newRoot;
}
void printTree(TreeNode<int> *root)
{
if (root == NULL)
{
return;
}
cout << root->data << " : ";
if (root->left != NULL)
{
cout << "L" << root->left->data << " ";
}
if (root->right != NULL)
{
cout << "R" << root->right->data << " ";
}
cout << endl;
printTree(root->left);
printTree(root->right);
}