Iteration Java solution


  • 1
    public boolean isValidBST(TreeNode root) {
            List<Integer> list = new ArrayList();
            Deque<TreeNode> stack = new ArrayDeque();
            TreeNode t = root;
            while (t != null || !stack.isEmpty()) {
                if (t != null) {
                    stack.push(t);
                    t = t.left;
                } else {
                    TreeNode node = stack.pop();
                    if (!list.isEmpty() && node.val <= list.get(list.size() - 1)) return false;
                    list.add(node.val);
                    t = node.right;
                }
            }
            return true;
        }
    

Log in to reply
 

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