Find two numbers in the binary search tree that add up to the third number

You are given BST numbers. You should find in it two numbers (a, b) such that a + b = S, in O (n) time and O (1) space.

What could be the algorithm?

One possible way would be to convert two BSTs into a doubly linked list, and then start from the front and the end:

if front + end > S then end--

Or:

if front + end < S then front++
+5
source share
3 answers

As already mentioned, you cannot solve this in the constant space O (1). In addition, all other currently proposed solutions use at least O (log ^ 2 n) space rather than O (log n): the stack has O (log n) frames, and each frame has an O-sized pointer (log n).

@dharm0us BST, . . , , , . O (log n) , O (log n) O (log ^ 2 n). O (n).

+3

. , .

: , , .

: . , . , , .

: ?

Me: . , .

: , . O (n). ?

Me ( ): Ok, BST , this algo. , . O (lg (n)) - .

+4

, , , , . O(1) space , ( O(log n)) (O(n)).

, , - O(n), . , . O(n), , .

, . , , .

To do this, you start the start pointer down to the leftmost node and the end pointer down to the righmost node value. You also save two variables to store the last movement (up or across, initially up) of each pointer, so that you can intelligently choose the next move ( front++and end--in your question).

You can then use the current pointers and recent movements along with the current amount to decide which pointer to move (and how).

+3
source

All Articles