Sobes.tech
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:

  1. Start from the root of the tree.
  2. Compare the sought value with the current node.
  3. If the values match — the element is found.
  4. If the sought value is less, move to the left subtree.
  5. If it is greater — to the right subtree.
  6. 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.

Explain how the data structure of a search tree… - sobes.tech