Binary Search Trees – Can Two Trees Have the Same Values but Different Structures?

binary treedata structures

Define a BST as: all left descendants <= n < all right descendants.

Then is it possible to build two binary search trees with different structures but the same exact values? Duplicate values are allowed.

Best Answer

Yes, there can be various BSTs consisting of the same numbers. Let's take the numbers 1, 2, 3.

If the order you add them to the tree is 1, 2, 3 then the tree would have 1 as root, 2 as it's right node and 3 as 2's right node.

If the order is 2, 1, 3 then the tree would have 2 as the root, 1 as the left node and 3 as the right node.

If the order is 3, 1, 2 then the tree would have 3 as the root, 1 as the left node and 2 as the right node of 1. etc.