[路飞]_js算法:leetcode 面试题 04.05-合法二叉搜索树

141 阅读1分钟

leetcode 面试题 04.05. 合法二叉搜索树

问题描述: 实现一个函数,检查一棵二叉树是否为二叉搜索树。

示例 1:

输入: 
    2
   / \
  1   3
输出: true

示例 2:

输入: 
    5
   / \
  1   4
     / \
    3   6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
     根节点的值为 5 ,但是其右子节点值为 4

思路: 递归

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
function isValid(root,lower,upper){
    if(root==null)return true;
   if(root.val<=lower||root.val>=upper){
       return false;
   }
   return isValid(root.left,lower,root.val)&&isValid(root.right,root.val,upper)
}
var isValidBST = function(root) {
    return isValid(root,-Infinity,+Infinity);
};