Binary search tree with strings


I have a book that explains the theory behind binary search tree in a very bad way i know that there is something about the order of both left and right child but i still cannot get the idea about one being greater than the other previous level.

Take for example this tree of strings:

Binary tree of names

(sorry for my paint) this example is taken directly from my book :)

Could someone explain the order to me ? what is the logic behind this?


Answers:


In a BST every node has at most a left child and a right child. Every node on the left of a given node is smaller than it, and every node on the right of a given node is greater than it. One of the consequences of this is that you can't have duplicate values, so I'm not sure if that example is exactly how the book has it.

In the example you have, the strings are ordered alphabetically. Taking the root node as an example, Bob comes before Karen, so Bob goes on Karen's left. Tom comes after Karen, so Tom goes on Karen's right. Looking at the tree as a whole, you can see that every node on Karen's left (Bob, Alan, Ellen) comes before Karen alphabetically and every node on Karen's right (Tom, Wendy) comes after Karen alphabetically. This pattern is the same no matter which node you look at.