Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have multiple valid BSTs for a given set of data?

Given a set of data in a binary search tree, like the numbers 1 to 10, is it possible for multiple balanced binary search trees to exist?

Or is there just one, unique balanced BST for that set of data?

Thanks

like image 461
user2305684 Avatar asked May 27 '13 01:05

user2305684


1 Answers

It all depends on the specific binary tree data structure being used, the insertion algorithm, the balancing criteria and the order of insertion, but yes - it's possible to have multiple equivalent and valid balanced BSTs for a given sequence of values.

For example, this is a valid Red/Black Tree where the numbers 1-10 were inserted in ascending order:

Red/Black Tree

On the other hand, this is a valid AVL Tree, where the numbers 1-10 were inserted exactly in the same order as in the Red/Black Tree:

AVL Tree

Clearly, the trees are not exactly the same - but the ordering and balancing properties hold for both.

like image 164
Óscar López Avatar answered Oct 02 '22 23:10

Óscar López