Skip to content

Instantly share code, notes, and snippets.

@thinkphp
Created April 22, 2017 05:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thinkphp/a60c6af8c28cc63dfd910ee78a1c81d5 to your computer and use it in GitHub Desktop.
Save thinkphp/a60c6af8c28cc63dfd910ee78a1c81d5 to your computer and use it in GitHub Desktop.
Binary Tree to Binary Search Tree Conversion
/* 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