Sobes.tech
Junior — Middle

Můžete vysvětlit, co je datová struktura binární vyhledávací strom a jak funguje?

sobes.tech AI

Odpověď od AI

Binární vyhledávací strom (Binary Search Tree, BST) je datová struktura ve tvaru stromu, kde každý uzel obsahuje klíč, a pro každý uzel platí následující podmínka:

  • Všechny klíče v levém podstromu jsou menší než klíč uzlu.
  • Všechny klíče v pravém podstromu jsou větší než klíč uzlu.

To umožňuje efektivní provádění operací hledání, vkládání a odstraňování prvků s průměrnou složitostí O(log n), pokud je strom vyvážený.

Příklad vkládání a hledání v BST v JavaScriptu:

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