Second Minimum Node In a Binary Tree — LeetCode 671
Published in
2 min readNov 24, 2022
Difficulty: Easy; Category: Tree
According to the question description, this special binary tree root
is with particular nodes that each node has two or zero sub-node and this node will be always smaller or equal to sub-nodes. And our aim is to find the second minimum node in this tree.
Since the parent node is always smaller or equal to its’ child node, we can consider the root node of the binary tree root
will be the smallest one. Then we just need to find the one which is just bigger than the root node.
Solution
class Solution:
def findSecondMinimumValue(self, root: Optional[TreeNode]) -> int:
self.min2 = float('inf')
min1 = root.val
def dfs(node):
if node:
if min1 < node.val < self.min2:
self.min2 = node.val
elif node.val == min1:
dfs(node.left)
dfs(node.right)
dfs(root)
return self.min2 if self.min2 < float('inf') else -1
- use float(‘inf’) to initialize our answer
self.min2
- as we mentioned above, assign
root.val
as the treeroot
’s minimum value:min1 = root.val
dfs
goes to each node to check whether the current node value is greater thanmin1
and less thanself.min2
. If it is, it means the node is the current second minimum. Assign this node value as ourself.min2
. And since we know that this node’s children will be always the same or larger than it, continuing thisdfs
is impossible to find a value between currentmin1
andself.min2
, so we could stop this dfs here- If the current node value is equal to
min1
, we go through its left node and right node to check if their node value could be the second minimum value - If the current node value is bigger than the current
self.min2
, it will impossible to be the second minimum value, so just skip processing of this condition - If the node of
dfs(node)
isNone
, it means we reach the end of the tree root, we could stop the dfs. - return
self.min2
if we found the second minimum value during the dfs, otherwise, return-1
that says there isn’t any second minimum value