98. Validate Binary Search Tree
public class Solution { public boolean isValidBST(TreeNode root) { Stack<TreeNode> stack=new Stack<TreeNode>(); TreeNode cur=null; while(root!=null||!stack.isEmpty()) { while(root!=null) { stack.push(root); root=root.left; } root=stack.pop(); if(cur!=null&&cur.val>=root.val) return false; cur=root; root=root.right; } return true; } }
class Solution { public boolean isValidBST(TreeNode root) { TreeNode cur=root, pre=null, p=null; while(cur!=null) { if(cur.left!=null) { p=cur.left; while(p.right!=null&&p.right!=cur) p=p.right; if(p.right==null) { p.right=cur; cur=cur.left; } else { if(pre!=null&&cur!=null&&pre.val>=cur.val) return false; pre=cur; p.right=null; cur=cur.right; } } else { if(pre!=null&&cur!=null&&pre.val>=cur.val) return false; pre=cur; cur=cur.right; } } return true; } }