A deep mine's ventilation system is laid out as a binary tree of duct junctions. Each junction is either a sealed sensor with no children, or it splits into exactly two child ducts. Cold, dense air always wins at a merge point, so every junction with two children reports a temperature equal to the minimum of its two children's readings. You are given the full network of readings and must report the second-coldest distinct temperature that appears anywhere in the tree.
n — the number of junctions (junction 1 is the mine's main outlet, i.e. the root).n lines describes junction i (for i from 1 to n, in that order) as three integers val_i left_i right_i:
val_i is the temperature reading at junction i.left_i and right_i are the 1-indexed junction numbers of its two children, or both 0 if junction i has no children.Every junction has either exactly zero children or exactly two children. Whenever a junction has two children, its reading is guaranteed to equal the minimum of its two children's readings.
Print a single integer: the second smallest distinct reading in the whole network, or -1 if fewer than two distinct readings exist.
1 <= n <= 25 (note that n is always odd, since every junction has 0 or 2 children).0 <= val_i <= 2^31 - 1.left_i, right_i are either 0 or valid junction indices, forming a single tree rooted at junction 1 with no cycles.Example 1
Input
5 2 2 3 2 0 0 5 4 5 5 0 0 7 0 0
Expected
5
Explanation
Junction 1 (root) reads 2, with children junction 2 (leaf, reads 2) and junction 3 (reads 5, with children junction 4 reading 5 and junction 5 reading 7). Check: junction 3's reading 5 = min(5,7); junction 1's reading 2 = min(2,5). The distinct readings across the whole network are {2, 5, 7}. The smallest is 2, so the second-coldest distinct reading is 5.
Example 2
Input
3 2 2 3 2 0 0 2 0 0
Expected
-1
Explanation
All three junctions read exactly 2, so there is only one distinct reading in the whole network. Since a second distinct reading does not exist, the answer is -1.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →