JAVASCRIPT
Binary Search Tree - تنفيذ كامل
تنفيذ كامل لشجرة البحث الثنائية مع عمليات الإدراج، البحث، والحذف. كفاءة O(log n) في المتوسط.
class BinarySearchTree {
constructor() {
this.root = null;
}
Node(value) {
return {
value,
left: null,
right: null
};
}
insert(value) {
const newNode = this.Node(value);
if (!this.root) {
this.root = newNode;
return this;
}
let current = this.root;
while (true) {
if (value === current.value) return undefined;
if (value < current.value) {
if (!current.left) {
current.left = newNode;
return this;
}
current = current.left;
} else {
if (!current.right) {
current.right = newNode;
return this;
}
current = current.right;
}
}
}
find(value) {
if (!this.root) return false;
let current = this.root;
while (current) {
if (value === current.value) return current;
current = value < current.value ? current.left : current.right;
}
return false;
}
remove(value) {
this.root = this._removeNode(this.root, value);
return this;
}
_removeNode(node, value) {
if (!node) return null;
if (value < node.value) {
node.left = this._removeNode(node.left, value);
} else if (value > node.value) {
node.right = this._removeNode(node.right, value);
} else {
if (!node.left && !node.right) return null;
if (!node.left) return node.right;
if (!node.right) return node.left;
const minRight = this._findMin(node.right);
node.value = minRight.value;
node.right = this._removeNode(node.right, minRight.value);
}
return node;
}
_findMin(node) {
while (node.left) node = node.left;
return node;
}
// In-order traversal (sorted)
inOrder() {
const result = [];
this._inOrder(this.root, result);
return result;
}
_inOrder(node, result) {
if (node) {
this._inOrder(node.left, result);
result.push(node.value);
this._inOrder(node.right, result);
}
}
}
// Usage
const bst = new BinarySearchTree();
bst.insert(10).insert(5).insert(15).insert(3).insert(7);
console.log(bst.inOrder()); // [3, 5, 7, 10, 15]
💡 مثال الاستخدام
استخدم BST لفرز البيانات ديناميكياً، البحث السريع، أو بناء Indexes فعالة.
استخدام حر
هذا الكود متاح للاستخدام الحر. إذا كان لديك أسئلة أو تحتاج مساعدة، لا تتردد في التواصل معي.