Searching

Searching a binary tree for a specific value can be a recursive or iterative process. This explanation covers a recursive method.

We begin by examining the root node. If the value we are searching for equals the root, the value exists in the tree. If the value we are searching for is less than the root, it must be in the left subtree. Similarly, if it is greater than the root, then it must be in the right subtree.This process is repeated on each subsequent node until the value is found or we reach a leaf node. If a leaf node is reached and the searched value is not found, then the item must not be present in the tree.

Here is an algorithm for Searching an element in binary search tree
---------------------------------------------------
def search_binary_tree(node, key):
if node is None:
return None # key not found
if key < node.key:
return search_binary_tree(node.left, key)
elif key > node.key:
return search_binary_tree(node.right, key)
else: # key is equal to node key
return node.value # found key
----------------------------------------------------

The part that is rebuilt uses T(log n) space in the average case and O(n) in the worst case.

In either version, this operation requires time proportional to the height of the tree in the worst case, which is O(log n) time in the average case over all trees, but O(n) time in the worst case.