|
| 1 | +class TreeNode { |
| 2 | + constructor(val, left, right) { |
| 3 | + this.val = (val === undefined ? 0 : val); |
| 4 | + this.left = (left === undefined ? null : left); |
| 5 | + this.right = (right === undefined ? null : right); |
| 6 | + } |
| 7 | +} |
| 8 | + |
| 9 | +/** |
| 10 | + * @param {TreeNode} root |
| 11 | + * @return {boolean} |
| 12 | + */ |
| 13 | +var isValidBST = function (root) { |
| 14 | + let leftAncestors = [], rightAncestors = []; |
| 15 | + |
| 16 | + const exploreLeft = (node, list) => { |
| 17 | + console.log(`exploreLeft`) |
| 18 | + console.log(node.val) |
| 19 | + // console.log(leftAncestors.concat([node.val])) |
| 20 | + // console.log(Math.min(...leftAncestors.concat([node.val]))) |
| 21 | + // console.log(node.val !== Math.min(leftAncestors.concat([node.val]))) |
| 22 | + if (node.val !== Math.min(...leftAncestors.concat([node.val]))) return false; |
| 23 | + leftAncestors.push(node.val); |
| 24 | + |
| 25 | + return true || exploreRight(node, list); |
| 26 | + } |
| 27 | + |
| 28 | + const exploreRight = (node, list) => { |
| 29 | + console.log(`exploreRight`) |
| 30 | + console.log(node.val) |
| 31 | + console.log(rightAncestors) |
| 32 | + if (node.val !== Math.max(...rightAncestors.concat([node.val]))) return false; |
| 33 | + rightAncestors.push(node.val); |
| 34 | + return true || exploreLeft(node, list); |
| 35 | + } |
| 36 | + |
| 37 | + let queue = [root]; |
| 38 | + |
| 39 | + while (queue.length > 0) { |
| 40 | + let curr = queue.shift(), left = curr.left, right = curr.right; |
| 41 | + |
| 42 | + if ((left?.val ?? -Infinity) >= curr.val || (right?.val ?? Infinity) <= curr.val) return false; |
| 43 | + |
| 44 | + if (null !== left) { |
| 45 | + queue.push(left); |
| 46 | + if (!exploreLeft(left, leftAncestors)) return false; |
| 47 | + } |
| 48 | + |
| 49 | + |
| 50 | + if (null !== right) { |
| 51 | + queue.push(right); |
| 52 | + if (!exploreRight(right, rightAncestors)) return false; |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + return true; |
| 57 | +}; |
| 58 | + |
| 59 | +// [3,1,5,0,2,4,6] |
| 60 | +let x = |
| 61 | + isValidBST(new TreeNode(3, |
| 62 | + new TreeNode(1, |
| 63 | + new TreeNode(0), |
| 64 | + new TreeNode(2) |
| 65 | + ), |
| 66 | + new TreeNode(5, |
| 67 | + new TreeNode(4), |
| 68 | + new TreeNode(6) |
| 69 | + ) |
| 70 | + )) |
| 71 | + |
| 72 | +console.log("Result") |
| 73 | +console.log(x) |
0 commit comments