Help : Merging Binary Search Trees

P

ptrSriram

Can someone help me with an algorithm to merge two binary search trees.

One method I thought of was to flatten both the trees into sorted
lists(inorder traversal),merge those two sorted lists, and build a
binary search tree from the new list.
But this seems to be expensive in terms of space. Can this be done more
efficiently ?
Please help me.
 
W

Walter Roberson

Can someone help me with an algorithm to merge two binary search trees.
One method I thought of was to flatten both the trees into sorted
lists(inorder traversal),merge those two sorted lists, and build a
binary search tree from the new list.
But this seems to be expensive in terms of space. Can this be done more
efficiently ?

That depends. There are a number of different types of binary trees.
Is there some particular property imposed on the trees you are
using, such as that they must be "balanced" ? Do your tree entries
have back-pointers or just downward pointers?
 
C

Chuck F.

Walter said:
That depends. There are a number of different types of binary
trees. Is there some particular property imposed on the trees
you are using, such as that they must be "balanced" ? Do your
tree entries have back-pointers or just downward pointers?

I think the question should be answered in terms of a minimal
organization. i.e. the fundamental data item should be very
similar to:

struct itemlink {
struct itemlink *left, *right;
void *dataptr;
};

together with some routine that will return a -1, 0, +1 comparison
result when passed two struct itemlink * pointers. Then the trees
to be merged are represented by two struct itemlink * pointers to
the roots of the two trees.
 
T

Thad Smith

ptrSriram said:
Can someone help me with an algorithm to merge two binary search trees.

One method I thought of was to flatten both the trees into sorted
lists(inorder traversal),merge those two sorted lists, and build a
binary search tree from the new list.
But this seems to be expensive in terms of space.

Why would it be expensive in space? If the data is in a tree, each item
should be held in a node with two or more pointers. You should be able
to link the items into list, merge them, and place them in another tree
without any additional space.
 

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
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top