Share my BST interval tree solution C++ No sorting!

I share this solution because my friend was asked in his FB interview. He was asked to do it without sorting, for a large stream of intervals. The solution can be interval tree, but that is too complicated. Here I maintain a BST of distinct intervals. We dont need to maintain all the intervals like interval tree. We will merge intervals while we inserting. The code did not balance the tree. That is why performance is still 500+ms.

Suppose we already have a BST of disjoint intervals. Given a new interval A, it will first find the toppest interval that has overlapping with A. Suppose it is B. Until now everything is easy. We simply traversed tree to reach this.

Then, it will try to expand interval B. Now it becomes tricky. There are 3 cases. 1 case is simple. For the other 2 cases, you will need to delete currentNode, because it is already merged. You need to always correctly maintain prevNode and direction, in order to merge correctly in next round. For 1 case, you can end there. For another case, you need to continue exploration.
The 2nd and 3rd case have duplicate code. However, I just keep it for better understanding.

The whole reason we can do this, is because: we will never meet a situation that we delete 1 node with 2 children but still keep its 2 children. If we remove 1 node, that means either his left or right is deleted. So, this is not really traditional node deletion in BST!!!!!!

I only share my code that insert a new interval to a BST. Other parts are simple.
Please see notes when we exploring left Children, comments are omitted when exploring right children.

Actually Interval tree is a better solution. BST interval tree is tedious, because as you see in the comments the node merge is tedious. If we turn to interval tree, the only question is how to retrieve the final result? That means we merge intervals later.

Basically, if you want to keep each BST node maintain one interval and keep each interval disjoint, it is not easy. Using interval trees, each node is still an interval, but 2 nodes can overlap. The insertion is then much easier. We defer the merging work when we need the final result.