আমাদের একটি জাভাস্ক্রিপ্ট ফাংশন লিখতে হবে BinarySearchTree ডেটা টাইপের প্রোটোটাইপ অবজেক্টে যা একটি ভ্যালু গ্রহণ করবে এবং খুঁজে বের করবে যে ভ্যালুটিটি BST-তে আছে কিনা।
উদাহরণ
// BST-এর জন্য একটি সিঙ্গেল Node ক্লাস
class Node {
constructor(value) {
this.value = value;
}
}
// BST-এর জন্য ক্লাস
// নোড ইনসার্ট এবং এক্সিস্টিং নোড সার্চ করার ফাংশন ধারণ করে
class BinarySearchTree {
constructor() {
this._root = null;
};
insert(value) {
let node = this, side = '_root';
while (node[side]) {
node = node[side];
if (value === node.value) {
return;
};
side = value < node.value ? 'left' : 'right';
};
node[side] = new Node(value);
};
contains(value) {
let current = this._root;
while (current) {
if (value === current.value) {
return true;
};
current = value < current.value ? current.left : current.right;
}
return false;
};
}
const tree = new BinarySearchTree();
for (let i = 0; i < 10; i++) {
tree.insert(Math.floor(Math.random() * 1000));
};
tree.insert(34);
console.log(tree.contains(34));
console.log(tree.contains(334));
আউটপুট
কনসোলে আউটপুট হবে -
true false