在 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
廣告