LeetCode.098.Validate Binary Search Tree 验证二叉搜索树BST

题目描述

98 Validate Binary Search Tree https://leetcode-cn.com/problems/validate-binary-search-tree/ Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees.

Example 1:

    2
   / \
  1   3

Input: [2,1,3]
Output: true

Example 2:

    5
   / \
  1   4
     / \
    3   6

Input: [5,1,4,null,null,3,6]
Output: false

Explanation: The root node's value is 5 but its right child's value is 4.


解题过程

递归,递归过程中返回子树的最大值和最小值,并判断是否符合 BST 的定义。 时间复杂度 O(n),空间复杂度 O(n)

递归

private static class SolutionV2020 {
    public boolean isValidBST(TreeNode root) {
        if (null == root) {
            return true;
        }
        return isBST(root, new int[2]);
    }

    // 判断 root 是否 BST,同时将 root 的最小最大值依次放入 minMax[]
    private boolean isBST(TreeNode root, int[] minMax) {
        if (root.left == null && root.right == null) {
            minMax[0] = root.val;
            minMax[1] = root.val;
            return true;
        }
        int min = root.val, max = root.val;
        if (root.left != null) {
            int[] leftMinMax = new int[2];
            boolean leftIsBST = isBST(root.left, leftMinMax);
            // 左子树非BST,或者左子树的最大值大于等于 root.val 时返回 false
            if (!leftIsBST || leftMinMax[1] >= root.val) {
                return false;
            }
            min = Math.min(min, leftMinMax[0]);
        }
        if (root.right != null) {
            int[] rightMinMax = new int[2];
            boolean rightIsBST = isBST(root.right, rightMinMax);
            // 右子树非BST,或者右子树的最小值小于等于 root.val 时返回 false
            if (!rightIsBST || rightMinMax[0] <= root.val) {
                return false;
            }
            max = Math.max(max, rightMinMax[1]);
        }
        minMax[0] = min;
        minMax[1] = max;
        return true;
    }
}

中序遍历过程中判断

BST 的中序遍历序列是升序序列,遍历过程中用一个变量 pre 保存上一个遍历的结点,每次和当前节点比较,若大于当前节点则返回 false


GitHub代码

algorithms/leetcode/leetcode/_098_ValidateBinarySearchTree.java https://github.com/masikkk/algorithms/blob/master/leetcode/leetcode/_098_ValidateBinarySearchTree.java