671. Second Minimum Node In a Binary Tree
Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node’s value is either equal to or greater than the values in its children. Find the second minimum value in the set made of all the nodes’ values in the whole tree.
If no such second minimum value exists, return -1
instead.
-1
.-1
.The traversal ensures that all elements are visited, and using a set naturally ensures uniqueness.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def findSecondMinimumValue(root: TreeNode) -> int:
if not root:
return -1
# This set will store unique values
unique_values = set()
def traverse(node):
if node:
# Add the value of the current node to the set
unique_values.add(node.val)
traverse(node.left)
traverse(node.right)
# Perform the traversal starting from the root
traverse(root)
# Convert the set to a sorted list
unique_values = list(unique_values)
if len(unique_values) <= 1:
return -1
first_min = min(unique_values)
second_min = float('inf')
for value in unique_values:
if first_min < value < second_min:
second_min = value
return second_min if second_min < float('inf') else -1
This solution ensures that we efficiently find and return the second smallest node value if it exists, or -1
otherwise.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?