Second Minimum Node In a Binary Tree - Problem

Given a special binary tree with a unique property, find the second smallest value among all nodes in the tree.

This isn't just any binary tree - it has a fascinating constraint: every parent node's value equals the minimum of its two children. More formally, root.val = min(root.left.val, root.right.val) always holds.

Tree Structure Rules:

  • Each node has either exactly 2 children or 0 children (leaf node)
  • All values are non-negative integers
  • Parent nodes always contain the smaller value of their children

Goal: Return the second minimum value in the entire tree, or -1 if no such value exists.

Example: In a tree with values [2, 2, 3], the minimum is 2 and the second minimum is 3.

Input & Output

example_1.py โ€” Basic Tree
$ Input: root = [2,2,3]
โ€บ Output: 3
๐Ÿ’ก Note: The tree has values 2, 2, and 3. The minimum is 2, and the second minimum is 3.
example_2.py โ€” Complex Tree
$ Input: root = [2,2,5,null,null,5,7]
โ€บ Output: 5
๐Ÿ’ก Note: The tree has values 2, 2, 5, 5, and 7. The minimum is 2, and the second minimum is 5.
example_3.py โ€” No Second Minimum
$ Input: root = [1,1,1]
โ€บ Output: -1
๐Ÿ’ก Note: All nodes have the same value (1), so there is no second minimum.

Constraints

  • The number of nodes in the tree is in the range [1, 25]
  • 1 โ‰ค Node.val โ‰ค 231 - 1
  • root.val == min(root.left.val, root.right.val) for each internal node
  • Each node has either 0 or 2 children

Visualization

Tap to expand
๐Ÿ† ChampionScore: 2Same Score2๐Ÿฅˆ Runner-up345โœ“ Explore paths with higher scoresโœ— Skip paths with same score as champion๐ŸŽฏ Answer: Second lowest score = 3
Understanding the Visualization
1
Root = Tournament Champion
The root has the lowest score (minimum value) in the entire tournament
2
Explore Different Scores
Only follow tournament paths where participants have higher scores than the champion
3
Skip Duplicate Champions
If a participant has the same score as the champion, their subtournament won't help us
4
Find Runner-up
The smallest score greater than the champion's score is our answer
Key Takeaway
๐ŸŽฏ Key Insight: Since the root is guaranteed to be the minimum (champion), we only need to explore subtrees where children have different values, making our search much more efficient!
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 5
28.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen