[LeetCode]Binary Tree Preorder Traversal@Python

Binary Tree Preorder Traversal

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

Example

Input: [1,null,2,3]
Output: [1,2,3]

Solution

# Recursively
class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        def preorder(root):
            if not root:
                return []
            return [root.val]+preorder(root.left)+preorder(root.right)
        return preorder(root)
# Iteratively
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

你可能感兴趣的:(leetcode,BST,stack,递归)