Inserting value to a sorted binary tree?

Printable View

• 02-14-2009
HappySmileMan
Inserting value to a sorted binary tree?
Just read this binary trees explanation (well, read it again, I read it ages ago and forgot it since I don't code much)

I think I understand it, but I'm not sure about one thing.
If you have a sorted tree and call insert(X) on the tree, it will find the appropriate location for it(by repeatedly travelling left or right until it finds an empty node, based on whether it's bigger or smaller than current one), and then insert it.
This should keep the tree sorted (I think anyway), but not balanced (obviously).

But if I called insert(7) on:
Code:

```    10   /  \   7  11  / \ 5  8```
I'd get the 7 being placed to the left of the 8, and the tree would no longer be sorted.
Is there a way of doing the insertion while keeping the tree sorted or would it just have to be resorted on such occurences?
(Which I guess wouldn't be too bad considering you'd only really have to resort the tree with root node at 8 AFAICT, not whole thing)
• 02-14-2009
Prelude
>I'd get the 7 being placed to the left of the 8, and the tree would no longer be sorted.
How do you figure that? Run your resulting tree through an in-order traversal and you'll find that it's perfectly sorted:
Code:

```      10     /    \   7      11  /  \ 5    8     /     7```
The order is 5, 7 (first one), 7 (second one), 8, 10, 11. The duplicate keys don't have to be directly adjacent in the structure. If you did that then you really would violate the binary search tree ordering rule.
• 02-14-2009
iMalc
It's sorted alright. Everything in the direction of the right child of the first seven will come out after it, and everything in the direction of the left child of the 8 will come out before it.

Not only is it sorted, but if implemented properly, the insertion routine is "stable" in that an item inserted after another item that is equal, will always come out after the first one in an in-order traversal.
• 02-15-2009
HappySmileMan
Ok then I understand now, I was just assuming that duplicates should be connected, looking back at it now I realise that it doesn't seem to make any difference to how it operates.