LeetCode: Validate Binary Search Tree Solution
Traverse in-order and validate the traversed resultApproach (In-Order Traversal)
If the result of in-order traversal is a incremental array, then it is a binary search tree
Implementation
1var isValidBST = function (root) {2 let inOrderTraversalOutput = []34 const inOrderTraversal = node => {5 if (!node) return67 inOrderTraversal(node.left)8 inOrderTraversalOutput.push(node.val)9 inOrderTraversal(node.right)10 }1112 inOrderTraversal(root)1314 for (let i = 1; i < inOrderTraversalOutput.length; i++) {15 if (inOrderTraversalOutput[i - 1] >= inOrderTraversalOutput[i]) {16 return false17 }18 }1920 return true21}
Approach (Recursion)
Traverse the tree updated max, min of each half
Implementation
1var isValidBST = function (root) {2 const recursion = (3 node,4 minLeft = Number.NEGATIVE_INFINITY,5 maxRight = Number.POSITIVE_INFINITY6 ) => {7 if (!node) return true89 const cond1 = minLeft < node.val && node.val < maxRight10 const cond2 = recursion(node.left, minLeft, node.val)11 const cond3 = recursion(node.right, node.val, maxRight)1213 return cond1 && cond2 && cond314 }1516 return recursion(root)17}
References
Comments
Loading comments...
Tags
leetcode
tree
binary tree
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.