[英]Checking if a Binary Search Tree is Valid javascript
我在網上遇到了這個問題,我找到了以下函數來檢查 BST 是否有效。 但是,我不完全理解的是 max/min 如何從 null 變為您可以比較的值。 所以在以下函數中:
//Give the recursive function starting values:
function checkBST(node) {
// console.log(node.right);
return isValidBST(node, null, null);
}
function isValidBST(node, min, max) {
console.log(min, max);
if (node === null) {
return true;
}
if ((max !== null && node.val > max) || (min !== null && node.val < min)) {
return false;
}
if (!isValidBST(node.left, min, node.val) || !isValidBST(node.right, node.val, max)) {
return false;
}
return true;
}
var bst = new BinarySearchTree(8);
bst.insert(3);
bst.insert(1);
bst.insert(6);
bst.insert(10);
bst.insert(4);
當您從左側的最低深度返回時,它將最低深度的值與其正上方的深度進行比較(即,當輸出 1 3 時)。 不知何故 min 從 null 變為 1,但我沒有看到如何,我認為您需要某種基本情況才能將最小值從 null 更改為其他內容......當我控制台時,我在控制台中得到了這個。每次運行記錄最小/最大。
null null
null 8
null 3
null 1
1 3
3 8
3 6
3 4
4 6
6 8
8 null
8 10
10 null
給定一個節點,驗證二叉搜索樹,確保每個節點的左手孩子都小於父節點的值,並且每個節點的右手孩子都大於父節點
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.righ = null;
}
}
class Tree {
constructor() {
this.root = null;
}
isValidBST(node, min = null, max = null) {
if (!node) return true;
if (max !== null && node.data >= max) {
return false;
}
if (min !== null && node.data <= min) {
return false;
}
const leftSide = this.isValidBST(node.left, min, node.data);
const rightSide = this.isValidBST(node.right, node.val, max);
return leftSide && rightSide;
}
}
const t = new Node(10);
t.left = new Node(0);
t.left.left = new Node(7);
t.left.right = new Node(4);
t.right = new Node(12);
const t1 = new Tree();
t1.root = t;
console.log(t1.isValidBST(t));
變量min
變為非空,因為您顯式調用
isValidBST(node.right, node.val, max)
您將 node.val 作為參數min
傳遞的位置。 必須是在您進行此調用時node.val
不為空;
另一種解決方案可能是:
const isValidBST = (
root,
min = Number.MIN_SAFE_INTEGER,
max = Number.MAX_SAFE_INTEGER
) => {
if (root == null) return true;
if (root.val >= max || root.val <= min) return false;
return (
isValidBST(root.left, min, root.val) &&
isValidBST(root.right, root.val, max)
);
};
檢查二叉搜索樹是否有效:
class BTNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
/**
*
* @param {BTNode} tree
* @returns {Boolean}
*/
const isBinarySearchTree = (tree) => {
if (tree) {
if (
tree.left &&
(tree.left.value > tree.value || !isBinarySearchTree(tree.left))
) {
return false;
}
if (
tree.right &&
(tree.right.value <= tree.value || !isBinarySearchTree(tree.right))
) {
return false;
}
}
return true;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.