Sobes.tech
Junior — Middle

Explain the concept of binary search tree and its main properties.

sobes.tech AI

Answer from AI

Binary Search Tree (BST) is a data structure where each node contains a key and two subtrees: left and right. Main properties:

  • For any node, all keys in the left subtree are less than the node's key.
  • All keys in the right subtree are greater than the node's key.
  • Subtrees are also binary search trees.

This allows efficient operations of search, insertion, and deletion in time proportional to the height of the tree (average — O(log n)).

Example in Python:

class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None

class BST:
    def __init__(self):
        self.root = None

    def insert(self, key):
        if not self.root:
            self.root = Node(key)
            return
        current = self.root
        while True:
            if key < current.key:
                if current.left:
                    current = current.left
                else:
                    current.left = Node(key)
                    break
            else:
                if current.right:
                    current = current.right
                else:
                    current.right = Node(key)
                    break