views:

322

answers:

1

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

What could be the algorithm?

One possible way could be two convert the BST to a doubly linked List and then start from the front and end:

if front + end > S then end--

Or:

if front + end < S then front++
+2  A: 

Try as I could, I'm not sure this is possible with a binary tree that has no parent pointers. O(1) space means you can neither use recursion (the stack growth is O(log n)) nor copying to a doubly linked list (O(n)).

The method you allude to is an O(n) time complexity solution but not with a normal binary tree. In fact, I answered a similar question in great detail here. That was solved with O(n) space but only because they weren't initially sorted.

It is possible with a tree containing parent pointers. If the child nodes have pointers to their parents, you can basically treat the tree as a doubly-linked list processed iteratively.

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

Then you can use the current pointers and last movements, along with the current sum, to decide which pointer to move (and how).

paxdiablo
Well when I said convert to doubly linked List, I didn't mean to copy the tree to a doubly List. I actually meant converting it to a doubly List by making the left,rgight pointers play the role of NEXT, PREVIOUS.
Geek
You can't make it a doubly linked list with just next/previous, not unless you use recursion. And recursion is out because of the O(1) space requirement.
paxdiablo
Made CW since I don't believe there's a solution within those requirements, unless parent pointers are allowed. I'll be happy if I'm proved wrong.
paxdiablo
Made CW = ? Will post if I find the solution :(
Geek
@Geek: Community wiki. Since I'm not actually providing an answer to your question, I mark the answer CW (no rep either way). That's because, while it's my belief no solution exists, I'm not sure, and there's almost certainly people out there who know more than I.
paxdiablo
I agree that the only way to get a solution involves one of the following relaxations:1. Parent pointers2. O(n log n) time3. O(log n) space
Andrey