Second Minimum Node In a Binary Tree

You are given a non-empty special binary tree of non-negative values. Every node has either **zero or two** children, and when a node has two children its value is the **smaller** of its two children's values: `root.val = min(root.left.val, root.right.val)`. Return the second smallest **distinct** value among all nodes of the tree. If no such value exists, return `-1`.

30:00

Second Minimum Node In a Binary Tree
easy
Free written solution
Topics
Companies

You are given a non-empty special binary tree of non-negative values. Every node has either zero or two children, and when a node has two children its value is the smaller of its two children's values: root.val = min(root.left.val, root.right.val).

Return the second smallest distinct value among all nodes of the tree. If no such value exists, return -1.

Example 1:
Input: {"root":[2,2,5,null,null,5,7]}
Output: 5
Constraints:
  • The number of nodes in the tree is in the range [1,25][1, 25].

  • 1≤Node.val≤231−11 \leq \text{Node.val} \leq 2^{31} - 1

  • root.val == min(root.left.val, root.right.val) for each internal node of the tree.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[2,2,5,null,null,5,7]}

Every parent is the min of its children, so the root (2) is the smallest value in the tree. We are looking for the smallest value strictly above 2.

first (root)

2

ans

-1

values above first, met so far

none yet

22557
current node
equals first: search below
above first: stop here
current ans
faded: skipped subtree
Variables
VariableValue
first2
ans-1
DepthFunction Call
Stack empty
0/5