All problems

Problem 910

Second Minimum Node In a Binary Tree

Easy · 10 pts · Tree, Depth-First Search

Problem

In this special binary tree every node has either zero or two children, and every node with children holds the smaller of its two children's values, so the root holds the minimum of the whole tree. Find the second smallest distinct value in the tree, or print -1 if all values are equal. Search below the root: a subtree whose root value is larger than the root's value can be cut off, since its minimum is that value.

Input

The first line contains N, the number of tokens. The second line contains N tokens describing the tree in level order (breadth-first, left to right), where 'null' marks a missing child, as on LeetCode. Every node has 0 or 2 children, and a parent's value is the minimum of its children's values.

Output

Print the second minimum value, or -1.

Constraints

1 <= number of nodes <= 25; 1 <= value <= 2^31 - 1

Example input

7
2 2 5 null null 5 7

Example output

5

Explanation

In the tree 2 2 5 null null 5 7, the distinct values are 2, 5 and 7. The second smallest is 5.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Binary Tree Paths Next: Maximum Binary Tree