- 验证二叉搜索树
给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。
有效 二叉搜索树定义如下:
- 节点的左子树只包含严格小于当前节点的数。
- 节点的右子树只包含 严格大于 当前节点的数。
- 所有左子树和右子树自身必须也是二叉搜索树。
示例 1:

输入:root = [2,1,3]
输出:true
示例 2:

输入:root = [5,1,4,null,null,3,6]
输出:false
解释:根节点的值是 5 ,但是右子节点的值是 4 。
提示:
- 树中节点数目范围在
[1, 104]内 -231 <= Node.val <= 231 - 1
二叉搜索树的中序遍历(左 中 右)正好是按从小到大排的,所以用中序遍历来解决该题较容易。
用递归来只需要记录前一个元素,然后按左 中 右递归即可。
java
public class hot {
public static void main(String[] args) { // 测试用
TreeNode treeNode1 = new TreeNode(2);
treeNode1.left = new TreeNode(1);
treeNode1.right = new TreeNode(3);
hot hot = new hot();
System.out.println(hot.isValidBST(treeNode1));
}
long pre = Long.MIN_VALUE;
public boolean isValidBST(TreeNode root) {
if(root.left == null && root.right == null){
return true;
}
boolean res = dfs(root);
return res;
}
public boolean dfs(TreeNode root){
if (root == null){
return true;
}
if (!dfs(root.left)){ // 左
return false;
}
if (root.val <= pre){ // 中
return false;
}
pre = root.val; // 记录前一个值
if (!dfs(root.right)){ // 右
return false;
}
return true;
}
}
以上为记录分享用,代码较差请见谅