Skip to content

Commit

Permalink
Convert BST to Greater Tree
Browse files Browse the repository at this point in the history
  • Loading branch information
Pranjal authored Aug 16, 2017
1 parent 38a5b1a commit 76f19cf
Showing 1 changed file with 69 additions and 0 deletions.
69 changes: 69 additions & 0 deletions ConvertBSTToGreaterTree.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void inorder(TreeNode* root, vector<int>& in){
if(!root){
return;
}
inorder(root->left, in);
in.push_back(root->val);
inorder(root->right, in);
}

int find(vector<int>& in, int key){
int start = 0, end = in.size()-1;

while(start <= end){
int mid = start + (end-start)/2;
if(in[mid] == key){
return mid;
}
else if(in[mid] > key){
end = mid-1;
}
else{
start = mid+1;
}
}

return -1;
}

TreeNode* make(TreeNode* root, vector<int>& in, vector<int>& sumV){
if(!root){
return NULL;
}

int index = find(in, root->val);
root->val = sumV[index];

root->left = make(root->left, in, sumV);
root->right = make(root->right, in, sumV);

return root;
}

TreeNode* convertBST(TreeNode* root) {
vector<int> in;
inorder(root, in);

vector<int> sumV(in.size(), 0);

int sum = 0;

for(int i = in.size()-1; i >= 0; i--){
sum += in[i];
sumV[i] = sum;
}

return make(root, in, sumV);
}
};

0 comments on commit 76f19cf

Please sign in to comment.