โหมด:
โหมดของชุดข้อมูลเป็นเพียงตัวเลขที่เกิดขึ้นบ่อยครั้งในชุดข้อมูลนั้น ตัวอย่างเช่น 3 คือโหมดของชุดข้อมูล 2, 3, 1, 3, 4, 2, 3, 1 ที่เกิดขึ้นเป็นส่วนใหญ่
แผนผังการค้นหาไบนารี
ต้นไม้ DS เป็นต้นไม้ค้นหาไบนารีที่ถูกต้องหากตรงตามเงื่อนไขต่อไปนี้ -
-
ทรีย่อยด้านซ้ายของโหนดมีเฉพาะโหนดที่มีคีย์น้อยกว่าหรือเท่ากับคีย์ของโหนด
-
แผนผังย่อยด้านขวาของโหนดมีเฉพาะโหนดที่มีคีย์มากกว่าหรือเท่ากับคีย์ของโหนด
-
ทั้งทรีย่อยด้านซ้ายและขวาจะต้องเป็นทรีการค้นหาแบบไบนารีด้วย
ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับ BST root เป็นอาร์กิวเมนต์เดียว 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