-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathbinary_tree_to_BST.cpp
33 lines (26 loc) · 1.08 KB
/
binary_tree_to_BST.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
// problem link: https://practice.geeksforgeeks.org/problems/binary-tree-to-bst/1
// idea is that inorder traversal of binary search tree is in sorted order
// so we first of traverse BT and store it in an array, then sort that array
// and then make new bst from it by just replacing data
void inorderTraversal(Node* root, vector<int> &binaryTree){
if(root == NULL) return;
inorderTraversal(root->left, binaryTree);
binaryTree.push_back(root->data);
inorderTraversal(root->right, binaryTree);
}
void makeBST(Node* root, vector<int> &binaryTree, int &idx){
if(root == NULL) return;
makeBST(root->left, binaryTree, idx);
root->data = binaryTree[idx];
idx++;
makeBST(root->right, binaryTree, idx);
}
Node *binaryTreeToBST (Node *root)
{
vector<int> binaryTree;
inorderTraversal(root, binaryTree);
sort(binaryTree.begin(), binaryTree.end());
int idx=0;
makeBST(root, binaryTree, idx);
return root;
}