Python standard DFS Solution 52ms

  • 1

    Standard DFS solution:

    class Solution:
        # @param {TreeNode} root
        # @return {string[]}
        def binaryTreePaths(self, root):
            self.res = set() # avoid duplicate
            self.DFS(root, [])
            return list(self.res) 
        def DFS(self, root, buff):
            if not root: return # no need to process
            buff.append(root.val) # visit this node
            if root.left or root.right: # if not a leaf node
                self.DFS(root.left, buff)
                self.DFS(root.right, buff)
                self.res.add('->'.join(map(str, buff))) # leaf node, add the entire route
            buff.pop() # must erase after visiting this level

Log in to reply

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