题解 | #判断是不是二叉搜索树#
判断是不是二叉搜索树
https://www.nowcoder.com/practice/a69242b39baf45dea217815c7dedb52b
/*
* function TreeNode(x) {
* this.val = x;
* this.left = null;
* this.right = null;
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return bool布尔型
*/
function isValidBST( root ) {
// write code here
console.log(root)
if (root === null) {
return true
}
if (!root.left && !root.right) {
return true
}
let left = root.left === null? -Infinity : root.left.val
let right = root.right === null? Infinity : root.right.val
let left_right = root.left.right === null? -Infinity : root.left.right.val
if ((left < root.val) && (root.val< right) && (left_right < root.val)) {
return isValidBST(root.left) && isValidBST(root.right)
}
else {
return false
}
}
module.exports = {
isValidBST : isValidBST
};