[LeetCode]Validate Binary Search Tree, 解题报告

来源:互联网 发布:阿里云学生9.9 编辑:程序博客网 时间:2024/05/22 06:55

题目

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.

思路

可能大家第一时间都会想到用递归处理,但是一定要注意的是这道题目不是单独的递归判断一个根节点和两个孩子就能解决问题的,如图所示:



如果这是单独判断每颗子树,都满足BST的要求,但是整体来看就不行了,因为根节点的左子树中有大于根节点的节点存在,右子树中有小于根节点的节点存在


因此,可以考虑上下界的方式,然后判断每颗根节点即可


AC代码

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public static boolean isValidBST(TreeNode root) {        return isValidBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);    }    public static boolean isValidBST(TreeNode root, int min, int max) {        if (root == null) {            return true;        }        if (root.val <= min || root.val >= max) {            return false;        }        return isValidBST(root.left, min, root.val) && isValidBST(root.right, root.val, max);    }}





0 0