惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
The Blog of Author Tim Ferriss
S
Securelist
D
Docker
The Register - Security
The Register - Security
GbyAI
GbyAI
Recorded Future
Recorded Future
Engineering at Meta
Engineering at Meta
Stack Overflow Blog
Stack Overflow Blog
云风的 BLOG
云风的 BLOG
P
Proofpoint News Feed
罗磊的独立博客
博客园 - 【当耐特】
F
Full Disclosure
WordPress大学
WordPress大学
腾讯CDC
小众软件
小众软件
大猫的无限游戏
大猫的无限游戏
D
DataBreaches.Net
SecWiki News
SecWiki News
L
Lohrmann on Cybersecurity
I
InfoQ
MyScale Blog
MyScale Blog
量子位
Cyberwarzone
Cyberwarzone
博客园 - 三生石上(FineUI控件)
The Hacker News
The Hacker News
F
Fortinet All Blogs
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Jina AI
Jina AI
博客园_首页
H
Help Net Security
K
Kaspersky official blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Webroot Blog
Webroot Blog
Blog — PlanetScale
Blog — PlanetScale
V
Vulnerabilities – Threatpost
Y
Y Combinator Blog
The Cloudflare Blog
P
Proofpoint News Feed
V
Visual Studio Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
T
Tailwind CSS Blog
爱范儿
爱范儿
P
Privacy International News Feed
Security Archives - TechRepublic
Security Archives - TechRepublic
The GitHub Blog
The GitHub Blog
C
Cybersecurity and Infrastructure Security Agency CISA
B
Blog RSS Feed

Lan小站-嗯,不错! - 算法刷题

17. 电话号码的字母组合 - Lan小站-嗯,不错! 77. 组合 - Lan小站-嗯,不错! 283. 移动零 - Lan小站-嗯,不错! 189. 轮转数组 - Lan小站-嗯,不错! 13. 罗马数字转整数 - Lan小站-嗯,不错! 14. 最长公共前缀 - Lan小站-嗯,不错! 28. 找出字符串中第一个匹配项的下标 双指针 - Lan小站-嗯,不错! 【Hot100】【一般】3. 无重复字符的最长子串 - Lan小站-嗯,不错! 【周赛】【简单】6362. 合并两个二维数组 - 求和法 - Lan小站-嗯,不错!
【简单】144. 二叉树的前序遍历 - Lan小站-嗯,不错!
Lan · 2023-02-09 · via Lan小站-嗯,不错! - 算法刷题

Lan

本文最后更新于2023年02月09日,已超过1220天没有更新,若内容或图片失效,请留言反馈。

题目

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

示例 1:
www.lanol.cn

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

示例 2:

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

输入:root = [1]
输出:[1]
提示:

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

进阶:递归算法很简单,你可以通过迭代算法完成吗?

解法

其实这种题目不难,我感觉烦的是数据结构,题目里面给个list,搞得我不好测试。
比如之前的链表,非得让我自己写个list和链表的转换才好进行调试。

from typing import Optional, List

from alo.common import TreeNode


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


if __name__ == '__main__':
    s = Solution()
    s.preorderTraversal(TreeNode(1, None, TreeNode(2, TreeNode(3), None)))

www.lanol.cn