কম্পিউটার টিউটোরিয়াল

জাভাস্ক্রিপ্টে ইউনিভ্যালুড বাইনারি সার্চ ট্রি যাচাই করা


ইউনিভ্যালুড বাইনারি সার্চ ট্রি

একটি বাইনারি সার্চ ট্রি ইউনিভ্যালুড হয় যদি ট্রি-এ সব নোডের মান একই হয়।

সমস্যা

আমাদের একটি জাভাস্ক্রিপ্ট ফাংশন লিখতে হবে যা একটি BST-এর রুট নেবে এবং true রিটার্ন করবে যদি এবং কেবল যদি ট্রিটি ইউনিভ্যালুড হয়, অন্যথায় false।

উদাহরণস্বরূপ, ট্রির নোডগুলো যদি থাকে –

const input = [5, 5, 5, 3, 5, 6];

তবে আউটপুট হবে –

const output = false;

উদাহরণ

কোডটি নিচের মতো –

class Node{ constructor(data) { this.data = data; this.left = null; this.right = null; }; }; class BinarySearchTree{ constructor(){ this.root = null; } insert(data){ var newNode = new Node(data); if(this.root === null){ this.root = newNode; }else{ this.insertNode(this.root, newNode); }; }; insertNode(node, newNode){ if(newNode.data < node.data){ if(node.left === null){ node.left = newNode; }else{ this.insertNode(node.left, newNode); }; } else { if(node.right === null){ node.right = newNode; }else{ this.insertNode(node.right,newNode); }; }; }; }; const BST = new BinarySearchTree(); BST.insert(5); BST.insert(5); BST.insert(5); BST.insert(3); BST.insert(5); BST.insert(6); const isUnivalued = (root) => { const helper = (node, prev) => { if (!node) { return true } if (node.data !== prev) { return false } let isLeftValid = true let isRightValid = true if (node.left) { isLeftValid = helper(node.left, prev) } if (isLeftValid && node.right) { isRightValid = helper(node.right, prev) } return isLeftValid && isRightValid } if (!root) { return true } return helper(root, root.data) }; console.log(isUnivalued(BST.root));

আউটপুট

কনসোলে আউটপুট হবে –

false
  1. জাভাস্ক্রিপ্টে বাইনারি সার্চ ট্রি

  2. জাভাস্ক্রিপ্টে বাইনারি ট্রি

  3. জাভাস্ক্রিপ্টে স্ট্রিং সার্চ করার পদ্ধতি

  4. বাইনারি সার্চ ট্রিতে উপাদান সার্চ করার C++ প্রোগ্রাম