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
Second Minimum Node: Special Binary Tree PropertyInput: [2,2,3]223Tree Property:parent = min(children)Key Insight:✓ Root = min value (2)✓ Left child = 2 (same as min)✓ Right child = 3 (> min)→ Second minimum = 3Output: 33Algorithm: Find smallest value > root in O(n) timeSpecial tree property: root.val = min(left.val, right.val)Return -1 if no second minimum exists (all values same)
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.
Asked in
LinkedIn 15 Amazon 12 Google 8
125.0K Views
Medium Frequency
~15 min Avg. Time
1.6K 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