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.
判断是不是二分查找树==中序遍历严格递增
public class Solution {
//记录前一个节点
TreeNode pre = null;
//中序遍历严格递增,即为BST
public boolean isValidBST(TreeNode root) {
if(root != null){
if(!isValidBST(root.left)) return false; //左子树
if(pre != null && pre.val >= root.val) return false; //当前节点 > 上一节点
pre = root; //更新上一节点
return isValidBST(root.right); //右子树
}
return true;
}
}