Validate Binary Search Tree

lc98 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.


    public boolean isValidBST(TreeNode root) {
        if ( root == null) return true;
        TreeNode prev = null;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        while (root != null || ! stack.isEmpty()){
            while ( root != null){
                stack.add (root);
                root = root.left;
            }
            TreeNode cur = stack.pop();
            if (prev == null){
                prev = cur;
            }else{
                if (prev.val >= cur.val){
                    return false;
                }
                prev = cur;
            }
            root = cur.right;
        }
        return true;
    }

    private TreeNode prev = null;
    public boolean isValidBST(TreeNode root) {
        if ( root == null ) return true;
        if ( ! isValidBST(root.left)) return false;
        if( prev != null && root.val <= prev.val) return false;
        prev = root;        
        if ( ! isValidBST(root.right) ) return false;
        return true;
    }

results matching ""

    No results matching ""