Second Minimum Node In a Binary Tree

EasyTreesdfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given the root of a special binary tree of non-negative integers. Every node has either zero or two children, and whenever a node has two children, its value equals the **smaller** of its two children's values. Return the second smallest **distinct** value in the whole tree. If every node holds the same value, return -1. Because of the min rule the root always holds the smallest value.

Examples

Input: root = [2,2,5,null,null,5,7]
Output: 5
The distinct values are 2, 5 and 7.
Input: root = [2,2,2]
Output: -1
Only the value 2 appears.

Constraints

  • 1 <= number of nodes <= 25
  • 0 <= Node.val <= 2^31 - 1
  • Every node has 0 or 2 children, and `node.val == min(node.left.val, node.right.val)` for internal nodes

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More dfs problems