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

推荐订阅源

F
Fortinet All Blogs
Attack and Defense Labs
Attack and Defense Labs
V2EX - 技术
V2EX - 技术
O
OpenAI News
S
Secure Thoughts
H
Heimdal Security Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Schneier on Security
Schneier on Security
H
Hacker News: Front Page
S
Security Affairs
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Vercel News
Vercel News
Microsoft Security Blog
Microsoft Security Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
P
Proofpoint News Feed
The Register - Security
The Register - Security
GbyAI
GbyAI
Cloudbric
Cloudbric
MongoDB | Blog
MongoDB | Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
K
Kaspersky official blog
Forbes - Security
Forbes - Security
Y
Y Combinator Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
Scott Helme
Scott Helme
Hacker News - Newest:
Hacker News - Newest: "LLM"
The Cloudflare Blog
Recorded Future
Recorded Future
人人都是产品经理
人人都是产品经理
Cyberwarzone
Cyberwarzone
C
CERT Recently Published Vulnerability Notes
Webroot Blog
Webroot Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
L
LangChain Blog
T
Tor Project blog
Microsoft Azure Blog
Microsoft Azure Blog
博客园_首页
Hacker News: Ask HN
Hacker News: Ask HN
Blog — PlanetScale
Blog — PlanetScale
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
B
Blog RSS Feed
N
News and Events Feed by Topic
阮一峰的网络日志
阮一峰的网络日志
I
Intezer
V
V2EX
T
Tailwind CSS Blog
SecWiki News
SecWiki News
NISL@THU
NISL@THU
C
Check Point Blog

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