Given a BST with unique integers and a number K. Find a pair ( a, b ) in BST such that
a + b = k.
Constraints:
You cannot change the structure of the tree, otherwise we could have converted it to sorted Doubly linked list and foiund the pair in O(N).
The approach should be in-place.
O(N) solution is needed.
I have thought of something related to running two pointers, one from left to right and the other from right from to left in the same way we do in case of finding pair in a sorted array. But, i could not get a clear picture of how to implement it?
As Samuel already said I also think your solution should work.
Two pointers or iterators, one from left to right (small to big) and one from right to left (big to small).
If (a + b) > k then iterate the right to left one (the next smaller value) else the other one (the next bigger value).
You can stop if a >= b
The runtime is linear even in case of unbalanced tree.
Every node is visited max one time.
I think real function recursion will become somewhat complicated in this case.
So better use two selfmade stacks to do the recursion in one function.
Something like that: