Python, BFS iterative


  • 0
    P
    def findSecondMinimumValue(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root is None:
            return -1
        queue, min_cur = [root], float("inf") # setting the min_cur to largest value
        while len(queue):
            current = queue.pop(0)
            # print(queue, min_cur, current.val)
            if current.val < min_cur and current.val != root.val:
                min_cur = current.val
            if current.left is not None:
                queue.append(current.left)
            if current.right is not None:
                queue.append(current.right)
        return -1 if min_cur == float("inf") else min_cur # if min_cur hasn't changed then tree has just single unique element(== root.val)
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.