Second Minimum Node In a Binary Tree - Problem
Given a non-empty special binary tree consisting of nodes with non-negative values, where each node in this tree has exactly two or zero child nodes. If the node has two child nodes, then this node's value is the smaller value among its two child nodes.
More formally, the property root.val = min(root.left.val, root.right.val) always holds.
Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' values in the whole tree. If no such second minimum value exists, output -1 instead.
Input & Output
Example 1 — Basic Case
$
Input:
root = [2,2,3]
›
Output:
3
💡 Note:
The tree has values {2, 3}. The minimum is 2 and the second minimum is 3.
Example 2 — No Second Minimum
$
Input:
root = [2,2,2]
›
Output:
-1
💡 Note:
All nodes have the same value 2, so there is no second minimum value.
Example 3 — Larger Tree
$
Input:
root = [2,2,5,null,null,5,7]
›
Output:
5
💡 Note:
The tree has values {2, 5, 7}. The minimum is 2 and the second minimum is 5.
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 of the tree.
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
Special binary tree where parent = min(left, right)
2
Tree Property
Root is always minimum, find next smallest
3
Output
Second minimum value or -1 if none exists
Key Takeaway
🎯 Key Insight: The root is always the minimum due to the tree property, so we only need to find the smallest value greater than the root value.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code