Junior — Middle
Môžete vysvetliť, čo je dátová štruktúra binárne vyhľadávacie strom a ako funguje?
sobes.tech AI
Odpoveď od AI
Binárne vyhľadávacie strom (Binary Search Tree, BST) je dátová štruktúra vo forme stromu, kde každý uzol obsahuje kľúč, a pre každý uzol platí nasledujúca podmienka:
- Všetky kľúče v ľavom podstrome sú menšie ako kľúč uzla.
- Všetky kľúče v pravom podstrome sú väčšie ako kľúč uzla.
Toto umožňuje efektívne vykonávanie operácií vyhľadávania, vkladania a odstraňovania prvkov s priemernou zložitosťou O(log n), ak je strom vyvážený.
Príklad vkladania a vyhľadávania v BST v JavaScripte:
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