একটি নতুন তৈরি বাইনারি ট্রিতে প্রথম সন্নিবেশটি মূলে একটি নোড তৈরি করে৷ আরও সন্নিবেশ বাইনারি সার্চ ট্রি সম্পত্তি অনুসারে সন্নিবেশ করা হবে বাম শিশুদের পিতামাতার চেয়ে ছোট এবং ডান শিশুদের পিতামাতার চেয়ে বড়।
আসুন দেখি কিভাবে আমরা কোড −
-এ এই অ্যালগরিদম বাস্তবায়ন করতে পারিউদাহরণ
insertIter(data) {
let node = new this.Node(data);
// Check if the tree is empty
if (this.root === null) {
// Insert as the first element
this.root = node; return;
}
let currNode = this.root;
while (true) {
if (data < currNode.data) {
// Set the value here as we've reached a leaf node
if (currNode.left === null) {
currNode.left = node;
break;
} else {
currNode = currNode.left;
}
} else {
// Set the value here as we've reached a leaf node
if (currNode.right === null) {
currNode.right = node;
break;
} else {
currNode = currNode.right;
}
}
}
} আসুন জেনে নেওয়া যাক এই ফাংশনটি কিভাবে কাজ করে। প্রথমে, আমরা চেক করি যে রুটটি একটি নাল মানে গাছ খালি আছে যদি হ্যাঁ তাহলে আমরা রুট হিসাবে নতুন নোড বরাদ্দ করি এবং আমাদের কাজ শেষ। যদি না হয়, আমরা একটি currNode ভেরিয়েবল তৈরি করি এবং এটিকে root-এ নির্দেশ করি। তারপরে আমরা পরীক্ষা করি যে আমাদের ডেটা currNode-এর চেয়ে কম কি না, যদি তা হয়, তাহলে আমরা পরীক্ষা করি এর বাম সন্তান নাল কিনা। যদি তা হয় তবে আমরা আমাদের ডেটা এখানে রাখি এবং প্রস্থান করি। অন্যথায় আমরা পুনরাবৃত্তি করতে থাকি যতক্ষণ না আমরা একটি পাতায় পৌঁছাই এবং অবশেষে সেখানে আমাদের ডেটা রাখি।
আপনি −
ব্যবহার করে এই ফাংশনটি পরীক্ষা করতে পারেনউদাহরণ
let BST = new BinarySearchTree(); BST.insertIter(10); BST.insertIter(15); BST.insertIter(5); BST.insertIter(50); BST.insertIter(3); BST.insertIter(7); BST.insertIter(12);
আমরা এই ফাংশনটিকে পুনরাবৃত্তিমূলকও করতে পারি। গাছগুলি সহজাতভাবে পুনরাবৃত্তিমূলক কাঠামো এবং আমরা এই পুনরাবৃত্ত সম্পত্তিটি মোটামুটি সহজে ব্যবহার করতে পারি। আসুন সন্নিবেশ −
এর একটি পুনরাবৃত্ত সংস্করণ দেখিউদাহরণ
insertRec(data) {
let node = new this.Node(data);
// Check if the tree is empty
if (this.root === null) {
// Insert as the first element
this.root = node;
} else {
insertRecHelper(this.root, node);
}
} আমাদের একটি সহায়ক ফাংশন তৈরি করতে হবে যা পুনরাবৃত্তি করতে পারে তবে আমরা এটিকে ক্লাসের একটি বৈশিষ্ট্য হিসাবে প্রকাশ করতে চাই না, তাই এই ফাংশনটি ক্লাস সংজ্ঞার বাইরে থাকবে৷
উদাহরণ
function insertRecHelper(root, node) {
if (node.data < root.data) {
// Set the value here as we've reached a leaf node
if (root.left === null) {
root.left = node;
} else {
// Recursively call this function with the left subtree
insertRecHelper(root.left, node);
}
} else {
// Set the value here as we've reached a leaf node
if (root.right === null) {
root.right = node;
} else {
// Recursively call this function with the right subtree
insertRecHelper(root.right, node);
}
}
} আপনি −
ব্যবহার করে এটি পরীক্ষা করতে পারেনউদাহরণ
let BST = new BinarySearchTree(); BST.insertRec(10); BST.insertRec(15); BST.insertRec(5); BST.insertRec(50); BST.insertRec(3); BST.insertRec(7); BST.insertRec(12);