Iterative Python Code 45ms ( DFS + Stack )


  • 0
    R
    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        # @param {TreeNode} root
        # @return {string[]}
        def binaryTreePaths(self, root):
            stack, re = [(root, [])], []
            while stack:
                node, string = stack.pop()
                if node:
                    string.append(str(node.val))
                    if node.right or node.left:
                        if node.right: stack.append((node.right, string[:])) 
                        if node.left:  stack.append((node.left, string[:])) 
                    else:
                        re.append(string)   
            return list(map('->'.join, re))
    

Log in to reply
 

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