Solution to "Second Minimum Node In a Binary Tree" on Leetcode.
1# Definition for a binary tree node.
2# class TreeNode:
3# def __init__(self, val=0, left=None, right=None):
4# self.val = val
5# self.left = left
6# self.right = right
7class Solution:
8 def findSecondMinimumValue(self, root: Optional[TreeNode]) -> int:
9 nodes = [root]
10 nums = set([root.val])
11 while nodes:
12 node = nodes.pop()
13 nums.add(node.val)
14
15 if node.right:
16 nodes.append(node.right)
17
18 if node.left:
19 nodes.append(node.left)
20
21 if(len(nums) >= 2):
22 return sorted(list(nums))[1]
23 else:
24 return -1
25
This code finds the second minimum value in a binary tree. It uses a depth-first search approach to traverse the tree. The code starts by creating an empty set called "nums" to store the unique values of the nodes. It also creates a list called "nodes" initialized with the root node of the tree. The while loop continues until there are no more nodes left in the "nodes" list. In each iteration, it pops a node from the list and adds its value to the "nums" set. This ensures that only unique values are stored. If the current node has a right child, it gets added to the "nodes" list for further exploration. Similarly, if it has a left child, it also gets added to the list. After the while loop ends, the code checks if there are at least two unique values in the "nums" set. If there are, it converts the set to a sorted list, and returns the second value (index 1). If there are not enough unique values, it returns -1. In summary, the code traverses the binary tree using depth-first search, collects the unique values in a set, and returns the second minimum value if it exists.
Solution to "Count Number of Texts" question on Leetcode.