Created
April 22, 2017 05:52
-
-
Save thinkphp/a60c6af8c28cc63dfd910ee78a1c81d5 to your computer and use it in GitHub Desktop.
Binary Tree to Binary Search Tree Conversion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* The Node structure is | |
struct Node | |
{ | |
int data; | |
Node* left; | |
Node* right; | |
}; */ | |
vector<int> vec; | |
void orderGo(Node *root) { | |
if(root!=NULL) { | |
vec.push_back(root->data); | |
orderGo(root->left); | |
orderGo(root->right); | |
} | |
} | |
void inorder(Node*root){ | |
if(root->left) inorder(root->left); | |
root->data = vec[0]; | |
vec.erase(vec.begin()); | |
if(root->right) inorder(root->right); | |
} | |
/*Your code here*/ | |
Node *binaryTreeToBST (Node *root) | |
{ | |
orderGo(root); | |
sort(vec.begin(), vec.end()); | |
inorder(root); | |
return root; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment