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 In a Binary Tree INPUT Special Binary Tree 2 2 3 Tree Property: root.val = min(left.val, right.val) 2 = min(2, 3) Input Array: 2 2 3 ALGORITHM STEPS (Single Pass Optimized) 1 Initialize min1 = root.val = 2 result = -1 (not found) 2 Traverse Tree DFS through all nodes Looking for second min 3 Check Each Node If val > min1 and (result=-1 or val smaller) 4 Update Result Node 3 > min1(2) result = 3 Execution Trace: Visit 2: val=min1, skip Visit 2: val=min1, skip Visit 3: 3>2, result=3 FINAL RESULT Second Minimum Found 2 min1 2 3 min2 Output: 3 OK - Found! Second smallest: 3 Key Insight: Since root always holds the minimum value of the tree, the second minimum must be a value greater than root.val. We traverse once, tracking the smallest value > min1. This gives O(n) time complexity with O(h) space for recursion stack, where h is tree height. TutorialsPoint - Second Minimum Node In a Binary Tree | Single Pass Optimized Approach
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