[Leetcode 98]判断有效的二叉搜索树Validate Binary Search Tree
题目
https://leetcode.com/problems/validate-binary-search-tree
判断所给二叉树是否是二叉搜索树
二叉搜索树:其值left *[2,2,2]这种相等的情况也不是搜索树 Given the A valid BST is defined as follows: Example 1: Example 2: 思路 参考:https://www.bilibili.com/video/BV1VK411N7vm 首先最直观的方法,从左到右值越来越大 想到使用中序遍历(左中右),将所有元素提取出来成list 如果是搜索树,则list里的元素值依次递增 再对list遍历,如果list[i+1] 遍历完成,返回true 法二 上面的思路遍历了两次,时间空间复杂度↑ 优化,在遍历时就开始判断 以root对半分 root左取值范围【负无穷,root值】 root右取值返回【root值,正无穷】 *注意因为这里int类型,题目说int_min/max都能取到,所有我们tmp出的初始正负无穷要用long,更大 代码 法一 https://www.cnblogs.com/inku/p/15163602.html 法二root
of a binary tree, determine if it is a valid binary search tree (BST).
Input: root = [2,1,3]
Output: true
Input: root = [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.
class Solution {
List
class Solution {
public boolean isValidBST(TreeNode root) {
return fun(root,Long.MIN_VALUE,Long.MAX_VALUE);//初始化最大最小值
}
public boolean fun(TreeNode root,Long min,Long max){
if (root==null)
return true;
boolean left=fun(root.left,min,(long)root.val);//root左边,最大不超过root,值越来越小
//反之,返回false
if(root.val<=min||root.val>=max)
return false;
boolean right=fun(root.right,(long)root.val,max);//root右边,最小不小于root,值越来越大
return left&&right;//二者中一个false,就为false
}
}