#671
Second Minimum Node In a Binary Tree
pupil · 530 · lc easy +28 · verified · 46% accepted · 2,001 likes · top 30%
Description
You are given a non-empty special binary tree where every node has either exactly two or zero children. For nodes with two children, the parent's value equals the smaller of the two children's values — formally, root.val = min(root.left.val, root.right.val).
Find the second smallest distinct value across all nodes in the tree. If no such value exists, return -1.
Example 1:
Input: root = [2,2,5,null,null,5,7]
Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.
Example 2:
Input: root = [2,2,2]
Output: -1
Explanation: The smallest value is 2, but there isn't any second smallest value.
Code
1
2
3
4
5
6
7
8
9