给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。
有效 二叉搜索树定义如下:
节点的左子树只包含 小于 当前节点的数。
节点的右子树只包含 大于 当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/validate-binary-search-tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
return process(root).isBST;
}
private Info process(TreeNode root){
if(root == null){
return null;
}
Info LeftInfo = process(root.left);
Info RightInfo = process(root.right);
int min = root.val;
int max = root.val;
boolean isBST = true;
if(LeftInfo != null){
min = Math.min(min,LeftInfo.min);
max = Math.max(max,LeftInfo.max);
//可以写成 isBST = LeftInfo.isBST;
isBST = isBST && LeftInfo.isBST;
}
if(RightInfo != null){
min = Math.min(min,RightInfo.min);
max = Math.max(max,RightInfo.max);
//不可以写成 isBST = RightInfo.isBST;
//否则会把左子树是否是二叉搜索树的结果覆盖掉
isBST = isBST && RightInfo.isBST;
}
if(LeftInfo != null && LeftInfo.max >= root.val){
isBST = false;
}
if(RightInfo != null && root.val >= RightInfo.min){
isBST = false;
}
return new Info(min,max,isBST);
}
private class Info{
private int min;
private int max;
private boolean isBST;
public Info(int min,int max,boolean isBST){
this.min = min;
this.max = max;
this.isBST = isBST;
}
}
}