LeetCode

Validate Binary Search Tree

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.

Java

public class Solution {
    public boolean isValidBST(TreeNode root) {  
       Stack<TreeNode> stack = new Stack<TreeNode>();
       TreeNode cur = root;
       TreeNode pre = null;

       while(!stack.empty() || cur != null) {
           if(cur != null) {
               stack.push(cur);
               cur = cur.left;
           } else {
               cur = stack.pop();
               if(pre != null && pre.val >= cur.val) {
                   return false;
               }
               pre = cur;
               cur = cur.right;
           }
       }
       return true;
    }  
}