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

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

1 min read 267 words
1 min read
ShareWhatsAppPost on X
  • 1The problem involves finding the second minimum value in a special binary tree where each node's value is the minimum of its two sub-nodes.
  • 2If no second minimum value exists, the function should return -1, indicating that all nodes have the same value.
  • 3The provided solution has a time complexity of O(n) and a space complexity of O(1), ensuring efficient traversal of the tree.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The problem involves finding the second minimum value in a special binary tree where each node's value is the minimum of its two sub-nodes."

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)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 8 October 2020 · 1 min read · 267 words

Part of AskGif Blog · coding

You might also like