Martin Martin - 5 months ago 43
Python Question

Binary Search Trees

This is some code found on wikipedia regarding BST :

# 'node' refers to the parent-node in this case
def search_binary_tree(node, key):
if node is None:
return None # key not found
if key < node.key:
return search_binary_tree(node.leftChild, key)
elif key > node.key:
return search_binary_tree(node.rightChild, key)
else: # key is equal to node key
return node.value # found key

Now here's a Binary Tree :

5 12
3 8 9 14
4 11

If I am searching for 11, and I follow the algorithm up there, I start with 10, I go right to 12, and then left to 9. And I reach the end of the tree without finding 11.
But 11 exists in my tree, it's just on the other side.

Can you please explain what are the restrictions in a Binary Tree for this algorithm to work on my tree ?



It's just because your tree is not a binary search tree: it is not ordered correctly. The BST is build as described in the algorithm actually. For instance in your tree: the node '9' is not at the right position because as 9 < 10 it should be under the left branch of your root node '10'. Same for '14' and '11' which should be on the right branch.

for instance a BST could sth like this:

  5    11
3   8    12