zoukankan      html  css  js  c++  java
  • 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%的用户

  • 相关阅读:
    定时机制
    选择排序
    二分插入排序
    无名管道pipe
    Makefile
    Python下划线与命名规范
    Django IDE 开发环境的搭建
    Apache如何添加虚拟目录
    在Eclipse下如何安装插件
    Python的模块、包等概念的理解
  • 原文地址:https://www.cnblogs.com/hereisdavid/p/15335608.html
Copyright © 2011-2022 走看看