मोड:
डेटा के एक सेट का मोड केवल वह संख्या है जो उस डेटा सेट में सबसे अधिक बार होती है। उदाहरण के लिए, 3 डेटासेट 2, 3, 1, 3, 4, 2, 3, 1 का मोड है क्योंकि यह सबसे अधिक बार होता है।
बाइनरी सर्च ट्री
एक ट्री DS एक वैध बाइनरी सर्च ट्री है यदि यह निम्न शर्तों को पूरा करता है:
एक नोड का बायां सबट्री केवल उस नोड की कुंजी से कम या बराबर कुंजी वाले नोड्स को समाहित करता है।
एक नोड का दायां सबट्री केवल उस नोड की कुंजी से अधिक या बराबर कुंजी वाले नोड्स को समाहित करता है।
बाएं और दाएं दोनों सबट्री भी बाइनरी सर्च ट्री होने चाहिए।
समस्या
हमें एक JavaScript फ़ंक्शन लिखना है जो BST रूट को एकमात्र आर्ग्युमेंट के रूप में लेता है। BST में डुप्लिकेट हो सकते हैं या सबसे अधिक संभावना है। हमें ट्री द्वारा संग्रहीत डेटा का मोड ढूंढकर वापस करना होगा।
कोड
class Node{ constructor(data) { this.data = data; this.left = null; this.right = null; }; }; class BinarySearchTree{ constructor(){ // root of a binary seach tree 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(1); BST.insert(3); BST.insert(3); BST.insert(2); BST.insert(3); BST.insert(2); const findMode = function(root) { let max = 1; const hash = {}; const result = []; const traverse = node => { if (hash[node.data]) { hash[node.data] += 1; max = Math.max(max, hash[node.data]); } else { hash[node.data] = 1; }; node.left && traverse(node.left); node.right && traverse(node.right); }; if(root){ traverse(root); }; for(const key in hash) { hash[key] === max && result.push(key); }; return +result[0]; }; console.log(findMode(BST.root));आउटपुट
कंसोल में आउटपुट होगा:
3