-
Notifications
You must be signed in to change notification settings - Fork 243
/
FlattenABSTToSortedList.cpp
71 lines (47 loc) · 1.42 KB
/
FlattenABSTToSortedList.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
// https://www.codingninjas.com/codestudio/problems/flatten-bst-to-a-sorted-list_1169459?leftPanelTab=0
#include <bits/stdc++.h>
/************************************************************
Following is the Binary Tree node structure
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;
}
};
************************************************************/
void getNodes(TreeNode<int>* root, vector<TreeNode<int>*> &nodes) {
if(root==NULL)
return;
getNodes(root->left, nodes);
nodes.push_back(root);
getNodes(root->right, nodes);
}
TreeNode<int>* flatten(TreeNode<int>* root)
{
if(root==NULL)
return root;
vector<TreeNode<int>*> nodes;
getNodes(root, nodes);
TreeNode<int>* newNode= new TreeNode<int>(nodes[0]->data);
newNode->left= NULL;
TreeNode<int>* currNode= newNode;
for(int i=1; i<nodes.size(); i++) {
TreeNode<int>* tempNode= new TreeNode<int>(nodes[i]->data);
tempNode->left=NULL;
currNode->right= tempNode;
currNode= tempNode;
}
return newNode;
}