98. 验证二叉搜索树

中序遍历

class Solution {
    public boolean isValidBST(TreeNode root) {

        ArrayList<Integer> list = new ArrayList<>();
        inorder(root, list);

        /**
         * 中序遍历得到列表,判断列表是否是升序
         */
        for (int i = 0; i < list.size() - 1; i++) {

            if (list.get(i) >= list.get(i + 1)){
                return false;
            }
        }

        return true;
    }

    public void inorder(TreeNode root, ArrayList<Integer> list){

        if (root == null){
            return;
        }

        inorder(root.left, list);
        list.add(root.val);
        inorder(root.right, list);
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(n)
 */

深度优先搜索

class Solution {
    public boolean isValidBST(TreeNode root) {

        return dfs(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }

    /**
     * 对于每一棵左子树,所有节点值必须小于根节点,右子树则大于根节点
     * 因此对每棵子树设置一个最大值和最小值,所有节点值需要在这个区间内
     */
    public boolean dfs(TreeNode root, long min, long max){

        if (root == null){
            return true;
        }

        if (root.val <= min || root.val >= max){
            return false;
        }

        return dfs(root.left, min, root.val) && dfs(root.right, root.val, max);
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(n)
 */

https://leetcode-cn.com/problems/validate-binary-search-tree/

posted @ 2022-01-05 16:04  振袖秋枫问红叶  阅读(28)  评论(0)    收藏  举报