Junior — Middle
Explain how the data structure of a search tree functions and how element search is performed within it.
sobes.tech AI
Answer from AI
A search tree is a data structure, usually a binary tree, in which each node satisfies the property: all elements in the left subtree are less than the node's value, and all elements in the right subtree are greater than or equal to it.
The search for an element in such a tree proceeds as follows:
- Start from the root of the tree.
- Compare the sought value with the current node.
- If the values match — the element is found.
- If the sought value is less, move to the left subtree.
- If it is greater — to the right subtree.
- Repeat steps 2–5 until the element is found or a leaf is reached (then the element is absent).
Example in Python:
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def search(root, key):
if root is None or root.key == key:
return root
if key < root.key:
return search(root.left, key)
else:
return search(root.right, key)
Thus, searching in a balanced tree occurs in O(log n) time.