FunctionRacerProblemsRace

Second Minimum Node in a Binary Tree

EasyTreesPython, JavaScript, TypeScript, Java, C++

You are given the root of a binary tree. In this special tree every node has either 0 or 2 children, and every inner node's value equals the smaller of its two children's values (so the root holds the smallest value in the tree). Return the second smallest distinct value in the whole tree, or -1 if all values are the same.

Trees appear in the tests in level order, with null for a missing child, like [3,9,20,null,null,15,7]. Each node is a TreeNode with .val, .left and .right; the class is already defined for you.

Example 1

root [2,2,5,null,null,5,7]
returns 5

The values are 2, 5, 7. The second smallest distinct value is 5.

Example 2

root [2,2,2]
returns -1

Only one distinct value.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Trees problems