# LeetCode: Validate Binary Search Tree Solution

Traverse in-order and validate the traversed result

## Approach (In-Order Traversal)

If the result of in-order traversal is a incremental array, then it is a binary search tree

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}var isValidBST = function (root) {2  let inOrderTraversalOutput = []3
4  const inOrderTraversal = node => {5    if (!node) return6
7    inOrderTraversal(node.left)8    inOrderTraversalOutput.push(node.val)9    inOrderTraversal(node.right)10  }11
12  inOrderTraversal(root)13
14  for (let i = 1; i < inOrderTraversalOutput.length; i++) {15    if (inOrderTraversalOutput[i - 1] >= inOrderTraversalOutput[i]) {16      return false17    }18  }19
20  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 true8
9    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)12
13    return cond1 && cond2 && cond314  }15
16  return recursion(root)17}```

Original problem

leetcode

tree

binary tree

## Next Post

LeetCode: Number of Islands

Aug 23, 2022

To be consistent, first find out how to make it easy

## Previous Post

LeetCode: Longest Palindrome

Aug 18, 2022

Trim odds

Search Posts