144. Binary tree preorder traversal

Given the root of a binary tree, return the preorder traversal of its nodes' values.

  • code
class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        self.res = []

        def pre(root):
            if root:
                self.res.append(root.val)
                pre(root.left)
                pre(root.right)

        pre(root)
        return self.res

  • code
class Solution:
    def preorderTraversal(self, root):
        ret = []
        stack = [root]
        while stack:
            node = stack.pop()
            if node:
                ret.append(node.val)
                stack.append(node.right)
                stack.append(node.left)
        return ret