Ctrl K

Runner-Up in the Tree

Easy
You are given the root of a binary tree. The root is known to hold the smallest value in the whole tree: no node stores a number below root.val. A knockout bracket works this way, for instance, if the smaller number wins every match and moves up. Take the set of all node values (duplicates count once) and return the second smallest value in it, that is, the smallest value strictly greater than the minimum. If the tree holds only one distinct value, return -1.
Example 1
root=tree_node([4, 4, 9, None, None, 9, 12]) → 9

The smallest value in the tree is 4 (it sits at the root), and the next one up is 9.

Example 2
root=tree_node([7, 7, 7, 7, 7]) → -1

Every node holds 7, so there is no second distinct value and the answer is -1.

Example 3
root=tree_node([3, 3, 3, 3, 8, 3, 5]) → 5

The distinct values are 3, 5 and 8; the second smallest is 5, even though 8 appears higher up in the tree.

Constraints
  • 1 ≤ number of nodes ≤ 100
  • 1 ≤ Node.val ≤ 2³¹ − 1
  • root.val ≤ Node.val for every node
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLeft, Node, Right EasyIdentical Trees EasyMirror-Image Tree EasyTree Height EasyEvenly Grown Tree Easy
loading Python…
Input
root=tree_node([4, 4, 9, None, None, 9, 12])
Expected
9

Run checks the first 3 tests in your browser. Submit checks all 117 tests on the server, hidden ones included.