Python 3   ||   1-10 lines, 3 versions w/example   ||   T/S: 98% / 99%
\nThe iterative version, with example:\n\nclass Solution:\n    def preorderTraversal(self, root: TreeNode) -> list[int]:\n\n                                    
\nThe iterative version, with example:\n```\nclass Solution:\n    def preorderTraversal(self, root: TreeNode) -> list[int]:\n\n                                            #  Ex: root = [1, 2,None, 3,4]\n        if not root: return []              #         __1\n        stack, ans = [root], []             #        /\n                                            #       2\n        while stack:                        #      / \\\n            node = stack.pop()              #     3   4\n            ans.append(node.val)            #\n                                            #     node     node.left   node.right  stack    ans\n            if node.right:                  #   \u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013  \u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013   \u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013   \u2013\u2013\u2013\u2013\u2013\u2013  \u2013\u2013\u2013\u2013\u2013\u2013\n                stack.append(node.right)    #                                       [1]     []\n            if node. left:                  #       1          2         None       [2]     [1]\n                stack.append(node.left )    #       2          3          4         [4,3]   [1,2]\n                                            #       3        None        None       [4]     [1,2,3]\n                                            #       4        None        None       [4]     [1,2,3,4]\n        return ans  \n```\n[https://leetcode.com/problems/binary-tree-preorder-traversal/submissions/577636662/](https://leetcode.com/problems/binary-tree-preorder-traversal/submissions/577636662/)\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*N*), in which *N* ~ count of nodes.\n\nThe recursive version:\n```\nclass Solution:\n    def preorderTraversal(self, root: TreeNode) -> list[int]:\n\n        def dfs(node):\n            if not node: return\n\n            ans.append(node.val)\n\n            dfs(node.left)\n            dfs(node.right)\n  \n            return   \n        \n        ans = []\n        \n        dfs(root)\n\n        return ans\n```\nAnd here\'s a one-liner:\n```\nclass Solution:\n    def preorderTraversal(self, root: TreeNode) -> list[int]:\n\n        return [] if not root else   ([root.val]+\n                self.preorderTraversal(root.left)+\n                self.preorderTraversal(root.right))\n```\n\n
['Python', 'Python3']