//中序遍历
var isValidBST = function(root) {
let stack = []
let inorder = -Infinity
while (stack.length || root !== null) {
while (root !== null) {
stack.push(root)
root = root.left
}
root = stack.pop()
// 如果中序遍历得到的节点的值小于等于前一个 inorder,说明不是二叉搜索树
if (root.val <= inorder) {
return false
}
inorder = root.val
root = root.right
}
return true
}
//递归调用
const helper = (root, lower, upper) => {
if (root === null) {
return true
}
if (root.val <= lower || root.val >= upper) {
return false
}
return helper(root.left, lower, root.val) && helper(root.right, root.val, upper)
}
var isValidBST = function(root) {
return helper(root, -Infinity, Infinity)
}