Python Extremely Easy To Understand (Beats 91%)


  • 5

    Based on the special property of the tree, we can guarantee that the root node is the smallest node in the tree. We just have to recursively traverse the tree and find a node that is bigger than the root node but smaller than any existing node we have come across.

    - Yangshun

    class Solution(object):
        def findSecondMinimumValue(self, root):
            res = [float('inf')]
            def traverse(node):
                if not node:
                    return
                if root.val < node.val < res[0]:
                    res[0] = node.val
                traverse(node.left)
                traverse(node.right)
            traverse(root)
            return -1 if res[0] == float('inf') else res[0]
    

  • 0
    K

    Is there a reason for making res a list?


  • 2
    B

    @keyanp I think it is because in Python 2 you cannot modify references to variables within functions outside of its scope. By wrapping the value in a list, it allows modification of the value without modifying the reference to the list variable. Alternatively you can use an instance variable like self.res = float('inf').


  • -1
    X

    You don't have to traverse all nodes.
    If a node value is larger than current second largest, not needs to traverse the branch.


Log in to reply
 

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