Inserting an equal value element

Programatt picture Programatt · Feb 21, 2012 · Viewed 18.5k times · Source

I am currently studying binary search trees, and I was wondering what do you do if you try to insert an element that is the same value as the root? Where does it go?

Answer

Unknown1987 picture Unknown1987 · Feb 21, 2012

The definition of BST is that it is a ordered set, thus duplicates are not allowed to be inserted. This is usually due to more complex structures being built atop the BST. Depending on the desired behavior, you may want to throw an exception, error or silently ignore when duplicates are inserted.

However, depending on your comparison function you can store duplicates on the left or right subtree, but remember to keep your traversals and insertion sides consistent.