Leetcode-144. Binary Tree Preorder Traversal 二叉树的前序遍历 -python

题目

给定一个二叉树,返回它的 前序 遍历。
链接:https://leetcode.com/problems/binary-tree-preorder-traversal/

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

Example:

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

思路及代码

  • 先序遍历
  • 中序遍历
  • 后序遍历

1. DFS Recursion

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        def dfs(node):
            if not node:
                return
            ans.append(node.val)
            dfs(node.left)
            dfs(node.right)
            
        ans = []
        dfs(root)
        return ans

2. Iteration

class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        ans = []
        if not root:
            return ans
        stack = []
        cur = root
        while cur or stack:
            while cur:
                ans.append(cur.val)
                stack.append(cur)
                cur = cur.left
            cur = stack.pop()
            cur = cur.right
        return ans

复杂度

T = O ( n ) O(n) O(n)
S = O ( n ) O(n) O(n)

你可能感兴趣的:(Leetcode)