Sobes.tech
Junior — Middle

Сиз маалыматтардын структурасы катары бинардык издөө дарагын түшүндүрө аласызбы жана ал кантип иштейт?

sobes.tech AI

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