package niuke.day1;
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.
confused what"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.
public class Validate_binary_search_tree {
public static void main(String[] args) {
TreeNode t1 = new TreeNode(10);
TreeNode t2 = new TreeNode(5);
TreeNode t3 = new TreeNode(15);
TreeNode t4 = new TreeNode(6);
TreeNode t5 = new TreeNode(20);
t1.left = t2;
t1.right = t3;
t3.left = t4;
t3.right = t5;
System.out.println(isValidBST(t1));
}
static TreeNode pre = null;
//还是按着左,中,右的顺序来,就相当于是一个递增数列,pre是跟进做前一个数,如果前一个数即pre大于现在的数就返回FALSE,
//否则就接着继续遍历,不断地更新pre
public static boolean isValidBST(TreeNode root) {
if(root == null)
return true; //如果递归到了叶子节点肯定两边都给返回true
if(!isValidBST(root.left)) //先判断左子树是否满足要求
return false;
if(pre != null) {
if(pre.val >= root.val) {
return false;
}
}
pre = root; //这里保证了跟进的是前面遍历过节点的最大值,就是根节点
//遍历的时候先遍历小根节点左子树,如果小根节点的左子树中有小于大根节点的数值,就返回false
//
return isValidBST(root.right);
}
}