BiruLyu
7/14/2017 - 7:51 PM

## 98. Validate Binary Search Tree(#1 recursive).java

``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
TreeNode cur = root, pre = null;
while (cur != null) {
if(cur.left == null) {
if (pre != null && cur.val <= pre.val) return false;
pre = cur;
cur = cur.right;
} else {
TreeNode temp = cur.left;
while (temp.right != null && temp.right != cur) {
temp = temp.right;
}
if (temp.right == null) {
temp.right = cur;
cur = cur.left;
} else {
if (pre != null && cur.val <= pre.val) return false;
temp.right = null;
pre = cur;
cur = cur.right;
}
}
}
return true;
}
}``````
``````/**
* Definition for binary tree
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isValidBST(TreeNode root) {
if (root == null || (root.left == null && root.right == null)){
return true;
}
Stack<TreeNode> s = new Stack<TreeNode>();
TreeNode cur = root;
TreeNode pre = null;
while(true) {
while (cur != null) {
s.add(cur);
cur = cur.left;
}
if (s.isEmpty()) {
break;
}
cur = s.pop();
if(pre != null && pre.val >= cur.val) {
return false;
}
pre = cur;
cur = cur.right;

}
return true;
}
}``````
``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isValidBST(TreeNode root) {
return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
}

public boolean isValidBST(TreeNode root, long minVal, long maxVal) {
if (root == null) return true;
if (root.val >= maxVal || root.val <= minVal) return false;
return isValidBST(root.left, minVal, root.val) && isValidBST(root.right, root.val, maxVal);
}
}``````