[LintCode]Validate Binary Search Tree
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: True if the binary tree is BST, or false
*/
boolean isFirstNode = true;
int lastVal;
public boolean isValidBST(TreeNode root) {
// 2015-4-1 inoder traversal
if (root == null) {
return true;
}
if (!isValidBST(root.left)) {
return false;
}
if (!isFirstNode && lastVal >= root.val) {
return false;
}
isFirstNode = false;
lastVal = root.val;
if (!isValidBST(root.right)) {
return false;
}
return true;
}
}