98. Validate Binary Search Tree[Medium]

98. Validate Binary Search Tree

Given the root of a binary tree, determine if it is a valid binary search tree (BST).

A valid 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.

Constraints:

  • The number of nodes in the tree is in the range [1, 10^4].
  • -2^31 <= Node.val <= 2^31 - 1

Example
image

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

思路

BST就是要保证左子树的值小于当前节点值,右子树的值大于当前节点值。
换句话说就是每一个节点的值都要小于某个值并大于某个值,那根节点就大于MIN_VALUE,小于MAX_VALUE,递归每一个节点

  • 如果是左子树,那就应该小于父节点的value,大于父节点的left
  • 如果是右子树,那就应该大于父节点的value,小于父节点的right

题解

    public boolean isValidBST(TreeNode root) {
	// 要用Long.类型最大值最小值,题目限制最大值是2^31-1,Integer最大值不够
        return dfsIsValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }

    public boolean dfsIsValidBST(TreeNode root, long left, long right) {
        if (root == null)
            return true;
        if (!(root.val > left && root.val < right))
            return false;

        return dfsIsValidBST(root.left, left, root.val) && dfsIsValidBST(root.right, root.val, right);
    }
posted @ 2023-02-08 15:05  AaronTanooo  阅读(24)  评论(0)    收藏  举报