Sobes.tech
Junior — Middle
105

Сіз бинарлы іздеу ағашы деректер құрылымы дегеніміз не және ол қалай жұмыс істейтіні туралы түсіндіре аласыз ба?

AI-дан жауап

sobes.tech AI

Бинарлы іздеу ағашы (Binary Search Tree, BST) — бұл әр түйінінде кілті бар ағаш түріндегі деректер құрылымы, мұнда әр түйін үшін келесі шарт орындалады:

  • Сол жақтағы барлық кілттер түйіннің кілтінен кем.
  • Оң жақтағы барлық кілттер түйіннің кілтінен үлкен.

Бұл іздеу, енгізу және жою операцияларын тиімді орындауға мүмкіндік береді, егер ағаш теңдестірілген болса, орташа күрделілігі O(log n).

JavaScript-те BST-те енгізу және іздеу мысалы:

class Node {
  constructor(key) {
    this.key = key;
    this.left = null;
    this.right = null;
  }
}

class BST {
  constructor() {
    this.root = null;
  }

  insert(key) {
    const newNode = new Node(key);
    if (!this.root) {
      this.root = newNode;
      return;
    }
    let current = this.root;
    while (true) {
      if (key < current.key) {
        if (!current.left) {
          current.left = newNode;
          break;
        }
        current = current.left;
      } else {
        if (!current.right) {
          current.right = newNode;
          break;
        }
        current = current.right;
      }
    }
  }

  search(key) {
    let current = this.root;
    while (current) {
      if (key === current.key) return true;
      current = key < current.key ? current.left : current.right;
    }
    return false;
  }
}

const tree = new BST();
tree.insert(10);
tree.insert(5);
tree.insert(15);
console.log(tree.search(5)); // true
console.log(tree.search(20)); // false