Java recursive solution with Stack


  • 0

    Use stack can avoid Integer.MAX_VALUE, Integer.MIN_VALUE edge case.

    public boolean isValidBST(TreeNode root) {
        return travel(root, new Stack<>());
    }
    
    private boolean travel(TreeNode root, Stack<Integer> stack) {
        if (root == null) { return true; }
        return travel(root.left, stack) && (stack.empty() || stack.pop() < root.val) && (stack.push(root.val) != null) && travel(root.right, stack);
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.