Problem 671 · LeetCode 671(opens in a new tab)
Second Minimum Node In a Binary Tree
EasyDepth-first search
You are given the root of a special binary tree. Every node holds a positive integer, and every node has either no children or exactly two. A node with two children always holds the smaller of its two children’s values.
Look at all the distinct values in the tree and return the second smallest one. If every node holds the same value, there is no second smallest: return −1.
Example 1
Input: root = [3, 3, 8, 3, 5, 8, 9] Output: 5 Why: the distinct values are 3, 5, 8, 9
2 more examples and the constraints
Example 2
Input: root = [6, 6, 6] Output: -1 Why: every node is 6, so there is no second value
Example 3
Input: root = [4, 7, 4] Output: 7 Why: only two values exist, and 7 is the larger
Constraints
- 1 ≤ number of nodes ≤ 25
- 1 ≤ node value ≤ 2,147,483,647
- Each node with children equals the smaller of its two children
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Collect every value, then sortO(n log n)
- DFS that stops above the minimumO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 25 nodes | Verdict |
|---|---|---|---|
| Collect every value, then sort | O(n log n) | Passes; ignores the shape | |
| DFS that stops above the minimum | O(n) | Best; skips whole subtrees |
n = number of nodes, h = tree height.
Edge cases to test
- One node. [5] has a single value, so the answer is −1.
- All values equal. [6, 6, 6] also gives −1.
- Largest possible value. [1, 1, 2147483647] must return 2,147,483,647, so do not use the largest int as "not found".
- Answer deep on the left. In [2, 2, 5, 2, 3, 5, 6] the 3 sits two levels down, below a node equal to the minimum.
Common mistakes
- Starting the best value at INT_MAX and returning −1 when it is unchanged, which fails when the answer really is 2,147,483,647.
- Returning the smaller child of the root, which misses smaller values deeper down the side that equals the root.
- Counting the minimum twice: the answer must be strictly bigger than the root value.
How to talk through it
- 1Clarify. Distinct values only? What if all nodes are equal? How big can a value be?
- 2Give the simple version. Collect every value, sort, take the second; O(n log n).
- 3Use the rule. The root is the minimum and values never shrink downward, so a node above the minimum ends the search on its path.
- 4Code the DFS. Return −1 for "nothing here" and combine the two children carefully.
- 5Test out loud. Run one node, all equal, and an answer of 2,147,483,647.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?