find numbers in BST

U

usgog

Given a binary search tree, how to find two numbers that can add up to
a given number K?
 
D

Daniel Pitts

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.
 
A

Andreas Leitgeb

Daniel Pitts said:
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.
 
R

Roedy Green

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,681
Members
48,796
Latest member
Greg L.

Latest Threads

Top