python o(n) bfs & dfs


  • 0
    Z

    dfs

    class Solution(object):
        def findSecondMinimumValue(self, root):
            def dfs(node):
                if node:
                    s.add(node.val)
                    dfs(node.left)
                    dfs(node.right)
            s = set()
            dfs(root)
            s.remove(min(s))
            return min(s) if s else -1
    
    # Runtime: 36 ms
    

    bfs

    class Solution(object):
        def findSecondMinimumValue(self, root):
            q, s = collections.deque([root]), set()
            while q:
                p = q.popleft()
                s.add(p.val)
                if p.left:
                    q.append(p.left)
                if p.right:
                    q.append(p.right)
            s.remove(min(s))
            return min(s) if s else -1
    
    # Runtime: 42 ms
    

Log in to reply
 

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