Given a binary search tree, how to find two numbers that can add up to
a given number K?
Christian - 05 Dec 2007 17:55 GMT
usgog@yahoo.com schrieb:
> Given a binary search tree, how to find two numbers that can add up to
> a given number K?
nice homework .. have much fun with it..
Daniel Pitts - 05 Dec 2007 18:13 GMT
> Given a binary search tree, how to find two numbers that can add up to
> a given number K?
Its quite simple, start at both ends and work your way toward K/2, or
start at K/2, and work your way out.

Signature
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>
Andreas Leitgeb - 05 Dec 2007 18:37 GMT
>> Given a binary search tree, how to find two numbers that can add up to
>> a given number K?
> Its quite simple, start at both ends and work your way toward K/2, or
> start at K/2, and work your way out.
I wonder, if a sorted double-linked list of the available numbers wouldn't
allow for a more efficient algorithm than a binary search tree.
Roedy Green - 06 Dec 2007 12:58 GMT
On Wed, 5 Dec 2007 09:45:41 -0800 (PST), "usgog@yahoo.com"
<usgog@yahoo.com> wrote, quoted or indirectly quoted someone who said
>Given a binary search tree, how to find two numbers that can add up to
>a given number K?
Here is a very primitive algorithm. Traverse the tree. For every
element, retraverse the tree looking for K-this.
Here is a more sophisticated algorithm:
You are looking for pairs of the form iand K-i.
So first traverse the tree and record in a java.util.BitSet which
numbers you find.
Now traverse the BitSet enumerating i looking at elements i and K-i.
see http://mindprod.com/jgloss/binary.html#BITSET

Signature
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
Roedy Green - 06 Dec 2007 12:59 GMT
On Wed, 5 Dec 2007 09:45:41 -0800 (PST), "usgog@yahoo.com"
<usgog@yahoo.com> wrote, quoted or indirectly quoted someone who said
>Given a binary search tree, how to find two numbers that can add up to
>a given number K?
here's another algorithm. Sort the elements. see
http://mindprod.com/jgloss/binarysearch.html

Signature
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com