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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code