给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
- 节点的左子树只包含小于当前节点的数。
- 节点的右子树只包含大于当前节点的数。
- 所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
输入: 2 / \ 1 3 输出: true
示例 2:
输入: 5 / \ 1 4 / \ 3 6 输出: false 解释: 输入为: [5,1,4,null,null,3,6]。 根节点的值为 5 ,但是其右子节点值为 4 。
public class IsValidBST98 {
double last = -Double.MAX_VALUE;
public boolean isValidBST(TreeNode root) {
//采用中序遍历
if (root == null) return true;
if (isValidBST(root.left)) {
if (last < root.val) {
last = root.val;
return isValidBST(root.right);
}
}
return false;
}
public static void main(String[] args) {
TreeNode t1 = new TreeNode(10);
TreeNode t12 = new TreeNode(5);
TreeNode t13 = new TreeNode(15);
TreeNode t14 = new TreeNode(6);
TreeNode t15 = new TreeNode(20);
t1.left = t12;
t1.right = t13;
t13.left = t14;
t13.right = t15;
IsValidBST98 v = new IsValidBST98();
v.isValidBST(t1);
}
}