Leetcode python 144. 二叉树的前序遍历

144. 二叉树的前序遍历

给你二叉树的根节点 root ,返回它节点值的 前序 遍历。

img

示例 1:
输入:root = [1,null,2,3]
输出:[1,2,3]

示例 2:
输入:root = []
输出:[]

示例 3:
输入:root = [1]
输出:[1]

示例 4:
输入:root = [1,2]
输出:[1,2]

img

示例 5:
输入:root = [1,null,2]
输出:[1,2]

提示:

  • 树中节点数目在范围 [0, 100]
  • -100 <= Node.val <= 100

递归

class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        res = []
        def dfs(root):
            nonlocal res
            if not root:
                return
            res.append(root.val)
            dfs(root.left)
            dfs(root.right)
        dfs(root)
        return res 

执行用时:32 ms, 在所有 Python3 提交中击败了68.44%的用户

内存消耗:15.1 MB, 在所有 Python3 提交中击败了11.48%的用户

迭代

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

执行用时:28 ms, 在所有 Python3 提交中击败了88.10%的用户

内存消耗:14.9 MB, 在所有 Python3 提交中击败了73.41%的用户

原文地址:https://www.cnblogs.com/hereisdavid/p/15335608.html