Recursive solution and iterative solution, very clean python code


  • 0

    Recursive

    class Solution(object):
        def preorderTraversal(self, root):
            return ([root.val] + sum(map(self.preorderTraversal, (root.left, root.right)), [])) if root else []
    

    Iterative

    class Solution(object):
        def traversal(self, root):
            stack = [root]
            while stack:
                node = stack.pop()
                yield node.val
                [stack.append(child) for child in (node.right, node.left) if child]
    
        def preorderTraversal(self, root):
            return list(self.traversal(root)) if root else []

Log in to reply
 

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