Second Minimum Node In a Binary Tree

easy tree dfs

Problem

Given a non-empty special binary tree where each non-leaf node has exactly two children and root.val == min(left.val, right.val), return the second minimum value in the tree, or -1 if it does not exist.

Inputroot = [2,2,5,null,null,5,7]
Output5
The smallest value is 2 (the root). The smallest value strictly greater than 2 is 5.

def find_second_minimum(root):
    first = root.val
    ans = [-1]
    def dfs(n):
        if not n:
            return
        if ans[0] != -1 and n.val >= ans[0]:
            return
        if n.val > first:
            ans[0] = n.val
        dfs(n.left); dfs(n.right)
    dfs(root)
    return ans[0]
function findSecondMinimumValue(root) {
  const first = root.val;
  let ans = -1;
  (function dfs(n) {
    if (!n) return;
    if (ans !== -1 && n.val >= ans) return;
    if (n.val > first) ans = n.val;
    dfs(n.left); dfs(n.right);
  })(root);
  return ans;
}
class Solution {
    int first; long ans = -1;
    public int findSecondMinimumValue(TreeNode root) {
        first = root.val; dfs(root);
        return (int) ans;
    }
    void dfs(TreeNode n) {
        if (n == null) return;
        if (ans != -1 && n.val >= ans) return;
        if (n.val > first) ans = n.val;
        dfs(n.left); dfs(n.right);
    }
}
int findSecondMinimumValue(TreeNode* root) {
    int first = root->val; long ans = -1;
    function<void(TreeNode*)> dfs = [&](TreeNode* n) {
        if (!n) return;
        if (ans != -1 && n->val >= ans) return;
        if (n->val > first) ans = n->val;
        dfs(n->left); dfs(n->right);
    };
    dfs(root); return (int) ans;
}
Time: O(n) Space: O(h)