[路飞]_每天刷leetcode_32(合法二叉搜索树Legal Binary Search Tree)

705 阅读1分钟

合法二叉搜索树(Legal Binary Search Tree)

LeetCode传送门合法二叉搜索树

题目

实现一个函数,检查一棵二叉树是否为二叉搜索树。

Implement a function to check if a binary tree is a binary search tree.

Example:

Input:
    2
   / \
  1   3
Output: true


Input:
    5
   / \
  1   4
     / \
    3   6
Output: false
Explanation: Input: [5,1,4,null,null,3,6].
     the value of root node is 5, but its right child has value 4.


思考线


解题思路

首先我们要明确什么是二叉搜索树?

二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树

知道了二叉搜索树,我们可以根据其中序遍历是一个严格递增函数来做这道题。代码如下

function isValidBST(root: TreeNode | null): boolean {
    let ins = -Infinity;
    function isBST(root): boolean {
        if (!root) return true;
        return isBST(root.left) && root.val > ins && ((ins = root.val) || true) && isBST(root.right);
    }
    return isBST(root);

};

而我们又知道递归都可以用迭代来进行优化,于是有了下面的代码

function isValidBST(root: TreeNode | null): boolean {
    const stack = [];
    let compare = - Infinity;
    while(stack.length || root) {
        while(root) {
            stack.push(root);
            root = root.left;
        }
        const node = stack.pop();
        if(node.val <= compare) {
            return false;
        }
        compare = node.val;
        root = node.right;
    }
    return true;
};

而我们也可以根据搜索树的性质设计一个递归函数helper(root, lower, upper)来递归判断以root为根的子树,判断子树种所有结点的值是否都在(l,r)的范围内。如果不在则返回false,如果在范围内继续递归调用检查它的左右子树是否满足,如果都满足才说明这是一棵二叉搜索树。

于是我们又有了第三种解法

function isValidBST(root: TreeNode | null): boolean {
    return helper(root, -Infinity, Infinity)
};

function helper(root: TreeNode | null, lower: number, upper: number): boolean {
    if (!root) return true;
    if(root.val <=lower || root.val >= upper) return false;
    return helper(root.left, lower, root.val) && helper(root.right, root.val, upper);

}

这就是我对本题的解法,如果有疑问或者更好的解答方式,欢迎留言互动。