Second Minimum Node In A Binary Tree Problem
Description
LeetCode Problem 671.
Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the propertyroot.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' value in the whole tree.
If no such second minimum value exists, output -1 instead.
Example 1:
Input: root = [2,2,5,null,null,5,7]
Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.
Example 2:
Input: root = [2,2,2]
Output: -1
Explanation: The smallest value is 2, but there isn't any second smallest value.
Constraints:
- The number of nodes in the tree is in the range [1, 25].
- 1 <= Node.val <= 2^31 - 1
- root.val == min(root.left.val, root.right.val)for each internal node of the tree.
Solution
Approach: DFS That Stops at Larger Values
Because every internal node equals the smaller of its two children, a node's value is the minimum of its whole subtree. Two facts follow:
- The root holds the minimum of the entire tree, call it
smallest. - Once we reach a node with
node.val > smallest, nothing below it can be smaller thannode.val. So that node is the best candidate its subtree has to offer, and we do not need to look further down.
Define search(node), the smallest value greater than smallest in the subtree, or -1 if there is none:
- A missing node gives
-1. - If
node.val > smallest, returnnode.val. - Otherwise
node.val == smallest: search both children and combine. If one side returns-1, return the other; otherwise return the smaller of the two.
The answer is search(root).
The detail to watch is the -1 sentinel: a plain min(left, right) would pick -1 over a real value. It is safe as a sentinel only because all node values are at least 1. Also note the answer can be 231 − 1, so do not use Integer.MAX_VALUE (or a similar maximum) to mean "not found".
Complexity: O(n) time, where n is the number of nodes, since each node is visited at most once. O(h) space for the recursion, where h is the height of the tree.
class Solution:
def findSecondMinimumValue(self, root: Optional[TreeNode]) -> int:
smallest = root.val # every node is the minimum of its subtree, so the root is the overall minimum
def search(node: Optional[TreeNode]) -> int:
"""Smallest value greater than `smallest` in this subtree, or -1 if there is none."""
if node is None:
return -1
if node.val > smallest:
return node.val # nothing below it is smaller, so stop here
left = search(node.left)
right = search(node.right)
if left == -1:
return right
if right == -1:
return left
return min(left, right)
return search(root)
Now write it from memory
Close the write-up and solve it yourself against the tests.