You are given the root of a binary tree in which every node has either exactly two children or none. Node values are positive integers, and for every node that has children, the node's value equals the smaller of its two children's values.
Return the second smallest distinct value among all the node values in the tree. Return -1 if no second smallest value exists, that is, if every node holds the same value.
Tree Encoding
Your function receives root as a TreeNode. The node type is provided for you, with val, left, and right fields.
The examples below write the tree as its level-order traversal, where null marks a missing child of a listed node and trailing nulls are omitted. That is only how the input is displayed; the decoding is done for you.
Constraints
The number of nodes in the tree is in the range [1,25].
Every node has either exactly two children or none.
1≤Node.val≤231−1
Node.val equals the smaller of its two children's values, for every node that has children.
Examples
Example 1
Input
root = [2, 2, 5, null, null, 5, 7]
root
Output
5
Explanation
The smallest value in the tree is 2, and the second smallest distinct value is 5.
Example 2
Input
root = [2, 2, 2]
root
Output
-1
Explanation
Every node holds the value 2, so there is no second smallest value.
Loading editor...
Run checks the sample cases; Submit runs every case.
Samples 2
Custom 0
passedwrong answertime limiterrorran, no expected valuenot run