在 JavaScript 中检查单值二叉搜索树
单值二叉搜索树
如果树中的每个节点都具有相同的值,则二叉搜索树是单值的。
问题
我们需要编写一个 JavaScript 函数,该函数接收 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(){
// 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(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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP