Find the Second Distinct Value in a Minimum-Parent Tree

Quick Overview

Find the second smallest distinct value in a tree whose internal nodes equal the smaller of their two children.

Find the Second Distinct Value in a Minimum-Parent Tree

Company: LinkedIn

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

### Problem The nonempty binary tree has either zero or two children per node, and each internal node equals the smaller value of its two children. Return the second smallest distinct value anywhere in the tree, or -1 if every node has the same value. ```cpp class Solution { public: int findSecondMinimumValue(TreeNode* root); }; ``` ### Examples **Example 1:** ```text root = [1,1,4,null,null,4,6] Output: 4 Explanation: Distinct values are 1,4,6. ``` **Example 2:** ```text root = [7,7,7] Output: -1 Explanation: Repeated copies of the minimum do not create a second distinct value. ``` ### Constraints - There are 1..25 nodes. Values are in 1..2147483647. Each internal node has two children and equals their smaller value. ### What a Strong Answer Covers - Return the smallest distinct value greater than the minimum. - Return -1 when there is no second value, including for a single node. ### Follow-up Questions - How would your answer change if each parent could hold any value? - How would you return the third smallest distinct value? ```hint Think about the root What does the parent rule tell you about the root's value compared with its descendants? ```

Overview: Find the second smallest distinct value in a tree whose internal nodes equal the smaller of their two children.

LinkedIn logo
LinkedIn
easySoftware EngineerOtherCoding & Algorithms
0
0

Problem

The nonempty binary tree has either zero or two children per node, and each internal node equals the smaller value of its two children. Return the second smallest distinct value anywhere in the tree, or -1 if every node has the same value.

class Solution {
public:
    int findSecondMinimumValue(TreeNode* root);
};

Examples

Example 1:

root = [1,1,4,null,null,4,6]
Output: 4
Explanation: Distinct values are 1,4,6.

Example 2:

root = [7,7,7]
Output: -1
Explanation: Repeated copies of the minimum do not create a second distinct value.

Constraints

  • There are 1..25 nodes. Values are in 1..2147483647. Each internal node has two children and equals their smaller value.

What a Strong Answer Covers Guidance

  • Return the smallest distinct value greater than the minimum.
  • Return -1 when there is no second value, including for a single node.

Follow-up Questions Guidance

  • How would your answer change if each parent could hold any value?
  • How would you return the third smallest distinct value?