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

推荐订阅源

博客园 - 【当耐特】
Help Net Security
Help Net Security
P
Proofpoint News Feed
J
Java Code Geeks
爱范儿
爱范儿
Last Week in AI
Last Week in AI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
F
Full Disclosure
Google DeepMind News
Google DeepMind News
H
Help Net Security
G
Google Developers Blog
Jina AI
Jina AI
Vercel News
Vercel News
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
L
Lohrmann on Cybersecurity
S
Schneier on Security
Microsoft Azure Blog
Microsoft Azure Blog
IT之家
IT之家
Security Archives - TechRepublic
Security Archives - TechRepublic
阮一峰的网络日志
阮一峰的网络日志
N
News and Events Feed by Topic
GbyAI
GbyAI
B
Blog
O
OpenAI News
博客园_首页
Cisco Talos Blog
Cisco Talos Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Hacker News: Ask HN
Hacker News: Ask HN
TaoSecurity Blog
TaoSecurity Blog
腾讯CDC
MongoDB | Blog
MongoDB | Blog
M
MIT News - Artificial intelligence
C
Cybersecurity and Infrastructure Security Agency CISA
Cyberwarzone
Cyberwarzone
Webroot Blog
Webroot Blog
Simon Willison's Weblog
Simon Willison's Weblog
Y
Y Combinator Blog
C
Cisco Blogs
A
Arctic Wolf
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
T
The Exploit Database - CXSecurity.com
Security Latest
Security Latest
AI
AI
W
WeLiveSecurity
aimingoo的专栏
aimingoo的专栏
The Register - Security
The Register - Security
Project Zero
Project Zero
H
Hackread – Cybersecurity News, Data Breaches, AI and More
N
Netflix TechBlog - Medium
Blog — PlanetScale
Blog — PlanetScale

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