File: second-minimum-node-in-a-binary-tree/solution.py

Date: 2026-06-06

Time: 19:01

Purpose

This file solves LeetCode 671: Second Minimum Node In a Binary Tree. It implements a DFS-based search over a "special" binary tree where every node's value equals the minimum of its subtree. The goal is to find the second-smallest distinct value in the tree, or -1 if no such value exists.

Key Components

TreeNode

Standard binary tree node with val, left, right. This is the shared tree node definition used across many solutions in this repo (the "Imported By" list confirms it's reused extensively via test files).

findsecondminimum_value(root) -> int

The main solver. Contract:

Patterns

DFS with pruning. The key insight is the tree's structural invariant: every parent's value equals the minimum of its children. Therefore root.val is the global minimum. The algorithm walks the tree looking for the smallest value strictly greater than root.val.

The pruning at line 27 (return when node.val > min_val) is correct because once a node has a value larger than the minimum, all of its descendants must be >= that value (by the tree's invariant). There's no point descending further — we already captured this node's value as a candidate.

Closure over mutable state. The nested dfs function uses nonlocal candidate to track the best second-minimum found so far, avoiding the need to pass and return state through recursive calls.

Dependencies

Imports: Only typing.Optional — no external libraries.

Imported by: Heavily referenced by test files across the repo. The TreeNode class defined here is the canonical tree node used in many other solutions' test suites (hundreds of test files import it). This makes TreeNode a de facto shared utility, even though it's defined inline rather than in a shared module.

Flow

1. Guard: if root is None, return -1.

2. Capture min_val = root.val — guaranteed global minimum by the tree invariant.

3. Initialize candidate = -1 (sentinel meaning "no second minimum found yet").

4. Run dfs(root):

5. Return candidate (still -1 if no distinct second value exists).

Invariants

Error Handling

None explicitly. An empty tree (root is None) returns -1. The sentinel -1 serves double duty as both "no answer" and the LeetCode-specified return value for that case. No exceptions are raised.

Topics to Explore

Beliefs