Python, Straightforward with Explanation


  • 2

    Say the value of the root is min1. If some node's value is larger, it might be the answer, but every descendant node will be at least as big, so we don't need to check them.

    def findSecondMinimumValue(self, root):
        self.ans = float('inf')
        min1 = root.val
    
        def dfs(node):
            if node:
                if min1 < node.val < self.ans:
                    self.ans = node.val
                elif node.val == min1:
                    dfs(node.left)
                    dfs(node.right)
    
        dfs(root)
        return self.ans if self.ans < float('inf') else -1
    

Log in to reply
 

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