Junior — Middle
Kas saaksite selgitada, mis on andmestruktuur binaarne otsingupuu ja kuidas see töötab?
sobes.tech AI
Vastus AI-lt
Binary Search Tree (BST) is a data structure in the form of a tree, where each node contains a key, and the following condition holds for each 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.
This allows efficient search, insertion, and deletion operations with an average complexity of O(log n), if the tree is balanced.
Example of inserting and searching in BST in JavaScript:
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