Tuesday, March 2, 2021

[LinkedIn Question][LeetCode] Second Minimum Node In a Tournament Tree

Problem: Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property root.val = min(root.left.val, root.right.val) always holds.

Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree.

If no such second minimum value exists, output -1 instead.

Example:

Input: root = [2,2,5,null,null,5,7]
Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.

Input: root = [2,2,2]
Output: -1
Explanation: The smallest value is 2, but there isn't any second smallest value.


Approach: We can use Pre-Order traversal to solve this problem.


Implementation in C#:

public int FindSecondMinimumValue(TreeNode root) 

{

        if (root == null)

        {

            return -1;

        }

        if (root.left == null)

        {

            return -1;

        }

        long secondMin = long.MaxValue;

        this.FindSecondMinimumValue(root, root.val, ref secondMin);

        return secondMin == long.MaxValue ? - 1 : (int)secondMin;

    }

    

    private void FindSecondMinimumValue(TreeNode node, int firstMin, ref long secondMin)

    {

        if (node != null)

        {

            if (node.val > firstMin && node.val < secondMin)

            {

                secondMin = node.val;

            }

            else if (node.val == firstMin)

            {

                this.FindSecondMinimumValue(node.left, firstMin, ref secondMin);

                this.FindSecondMinimumValue(node.right, firstMin, ref secondMin);

            }

        }

    }


Complexity: O(n)

No comments:

Post a Comment