```
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;
```