leetcode-判断是否为搜索二叉树(BST/排序二叉树)-javasript实现

/*
 * function TreeNode(x) {
 *   this.val = x;
 *   this.left = null;
 *   this.right = null;
 * }
 */

/**
  * 
  * @param root TreeNode类 
  * @return bool布尔型
  */
function findleft(root)
{
    while(root.left)
    {
        root = root.left;
    }
    return root;
}
function findright(root)
{
    while(root.right)
    {
        root=root.right;
    }
    return root;
}
function isValidBST( root ) {
    // write code here
    if(root===null)
    {
        return true;
    }
    if(root.left)
    {
        if(findright(root.left).val>=root.val)
        {
            return false;
        }
    }
    if(root.right)
    {
        if(findleft(root.right).val<=root.val)
        {
            return false;
        }
    }
    return isValidBST(root.left) && isValidBST(root.right)
    
}
module.exports = {
    isValidBST : isValidBST
};

猜你喜欢

转载自blog.csdn.net/qq_42099097/article/details/107318047