Problem Description
A special binary tree is given where each node has either two children or none. For every internal node, its value is equal to the minimum of its two children. The task is to find the second minimum distinct value in the entire tree. If such a value does not exist, return -1.
Key Insights
- The root holds the smallest value in the tree.
- Only nodes with a value larger than the root are candidates for the second minimum.
- Use depth-first search (DFS) to traverse the tree and update the potential second minimum value.
- The tree's special property helps eliminate unnecessary comparisons during traversal.
Space and Time Complexity
Time Complexity: O(n) where n is the number of nodes in the tree. Space Complexity: O(h) where h is the height of the tree (recursive call stack).
Solution
Use a DFS approach to traverse the tree starting from the root. The root's value is established as the smallest value. As you traverse, if a node's value is greater than the root and less than the current candidate for second minimum, you update the candidate. If a node’s value is exactly equal to the smallest value, continue traversing its children. This approach leverages the tree's property to efficiently search for the second smallest unique value. Finally, return the candidate if found, otherwise return -1.