# C++ Summary for Binary Tree Problem Set 2

• Given an array of integers, replace every element with the least greater element on its right side in the array. If there are no greater element on right side, replace it with -1.

A tricky solution would be to use Binary Search Trees. We start scanning the array from right to left and insert each element into the BST. For each inserted element, we replace it in the array by its inorder successor in BST. If the element inserted is the maximum so far (i.e. its inorder successor doesn’t exists), we replace it by -1.

``````
class solution {
void insert(TreeNode*& root, int val, TreeNode*& succ) {
if(root == nullptr)
root = new TreeNode(val);
if (val < root->val) {
succ = root;
insert(root->left, val, succ);
}
else if (val > root->val)
insert(root-right, val, succ);
}

vector<int> replace(vector<int> a) {
int n = (int)a.size();
TreeNode* root = nullptr;
vector<int> result(n);
for (int i = n - 1; i >= 0; i--) {
TreeNode* succ = nullptr;
insert(root, a[i], succ);
if (succ)
result[i] = succ->val;
else
result[i] = -1;
}
return result;
}
};
``````

• @fight.for.dream Thanks for posting. Is this the correct category for this post?

If this is an actual interview question, could you please specify the company so I can move it to the correct subcategory? If it is just for your practice, maybe it's more appropriate to move to the General Discussion category.

• @fight.for.dream I have moved this topic to General Discussions category as well, since I am not sure if this is a real interview question. Please let me know otherwise and I will move it to the correct category, thanks.

• @1337c0d3r Ok, I will post the summary post in the general discussion parts ! Thanks !

• @fight.for.dream A hint for you, you can add a unique tag to all your summary posts, which will enable others to search all your summary posts easily. Thanks.

• @1337c0d3r Hi, how could I add unique label, should I create an unique id label ?

• @fight.for.dream You will need to edit your topic, then add the tag following the instructions here: