Blogs Hub

by Sumit Chourasia | Oct 08, 2020 | Category :coding | Tags : algorithm binary-tree data-structure easy leetcode tree

Second Minimum Node In a Binary Tree - Tree - Easy - LeetCode

Second Minimum Node In a Binary Tree - Tree - Easy - LeetCode

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 1:

Input: 
    2
   / \
  2   5
     / \
    5   7

Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.
 

Example 2:

Input: 
    2
   / \
  2   2

Output: -1
Explanation: The smallest value is 2, but there isn't any second smallest value.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution {
    public int FindSecondMinimumValue(TreeNode root) {
        
        if(root==null){
            return -1;
        }
        int min = int.MaxValue;
        int min2 = int.MaxValue;
        bool maxIntPresent = false;
        var queue = new Queue<TreeNode>();
        queue.Enqueue(root);
        while(queue.Count()>0){
            var node = queue.Dequeue(); 
            if(node.val == int.MaxValue){
                maxIntPresent = true;
            }
            if(node.val<min){
                min2 = min;
                min = node.val;                
            }
            else if(node.val<min2 && node.val!=min){
                min2=node.val;
            }
            
            if(node.left!=null){
                queue.Enqueue(node.left);
            }
            if(node.right!=null){
                queue.Enqueue(node.right);
            }
        }
        
        if(maxIntPresent){
            return min2;
        }
        return min2==int.MaxValue?-1:min2;
    }
}

Time Complexity: O(n)

Space Complexity: O(1)