JAVA non-recursive way with stack


  • 0
    I
            Stack<TreeNode> stack = new Stack<>();
            int ans = -1;
            for (TreeNode p = root; p != null || !stack.empty();) {
                if (p == null) {
                    p = stack.pop();
                } else if (p.val > root.val) {
                    if (ans < 0) ans = p.val;
                    else ans = Math.min(ans, p.val);
                    p = null;
                } else {
                    if (p.left != null) stack.push(p.right);
                    p = p.left;
                }
            }
            return ans;
    

Log in to reply
 

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