Time: 10 minutes
Just use the increasing property of in-order traversal of the binary search tree
- In-order traversal to find the left child
- Does pre exist?
- If not, assign , find the right child, and return 1
- If it exists, is it less than val?
- If yes, do not increment, and return false
- If not, increment, assign pre, and return 1
var isValidBST = function(root) {
var preVal = null var DFS = function(root) {
var left = true var right = true if (root.left) {
left = DFS(root.left)
}
if (preVal !== null) {
if (preVal >= root.val) return false preVal = root.val } else {
preVal = root.val }
if (root.right) {
right = DFS(root.right)
}
return left && right
}
return DFS(root)
};