当前位置:网站首页>LeetCode 0144. 二叉树的前序遍历:二叉树必会题
LeetCode 0144. 二叉树的前序遍历:二叉树必会题
2022-07-29 19:59:00 【Tisfy】
【LetMeFly】144.二叉树的前序遍历:二叉树必会题
力扣题目链接:https://leetcode.cn/problems/binary-tree-preorder-traversal/
给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
示例 1:

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

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

输入:root = [1,null,2] 输出:[1,2]
提示:
- 树中节点数目在范围
[0, 100]内 -100 <= Node.val <= 100
进阶:递归算法很简单,你可以通过迭代算法完成吗?
方法一:DFS
前序遍历的遍历顺序是:
根 → 左子树 → 右子树
这很明显地是个递归。
因此,我们可以构造一个DFS函数
void DFS(TreeNode* root);
来处理以root为根时的遍历。
递归终止条件:root为空。
函数内容:
先遍历得到这个节点的值,然后递归左子树,再递归右子树。
- 时间复杂度 O ( N ) O(N) O(N),其中 N N N是二叉树节点的个数
- 空间复杂度 O ( N ) O(N) O(N)
AC代码
C++
class Solution {
private:
vector<int> ans;
void dfs(TreeNode* root) {
if (!root) // 递归终止条件
return;
ans.push_back(root->val); // 先遍历得到这个节点的值
dfs(root->left); // 遍历左子树
dfs(root->right); // 遍历右子树
}
public:
vector<int> preorderTraversal(TreeNode* root) {
dfs(root); // 前序遍历
return ans;
}
};
同步发文于CSDN,原创不易,转载请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/126057536
边栏推荐
猜你喜欢

7 行代码搞崩溃 B 站,原因令人唏嘘!

关于论青少年尽早学少儿编程之说

Single-core browser and what is the difference between dual-core browser, which to use?

The difference between analog, digital and switching

8.2实训任务 Sqoop的安装与配置

聚丙烯微孔膜的等离子体改性及DNA|有机自由基改性DNA-阳离子脂质复合体的应用

Thesis writing strategy | how to write an academic research paper
![[mathematical foundation] higher mathematics concept learning](/img/59/3e1608de63c60201b3e7aaaf032d42.png)
[mathematical foundation] higher mathematics concept learning

conda虚拟环境 | install 与 list 问题

Detailed explanation of design ideas of webUI test framework
随机推荐
mysql get field comments and get table fields
论文写作全攻略|一篇学术科研论文该怎么写
【无标题】
Private domain growth | Private domain members: 15 case collections from 9 major chain industries
Thesis writing strategy | how to write an academic research paper
Verilog的时间格式系统任务----$printtimescale、$timeformat
JSP Servlet JDBC MySQL CRUD 示例教程
促进二十一世纪创客教育的新发展
offsetwidth111[通俗易懂]
JSP Servlet JDBC MySQL CRUD Sample Tutorial
使用IDEA连接mysql
JMeter usage tutorial (2)
Where is Naive Bayes "naive"?
Samba server configuration (when a server is required)
C语言学习书籍(提高篇)
图床软件要收费,算了我自己写一个开源免费的。
叶酸&适配体修饰DNA纳米载体|CdS纳米颗粒修饰DNA|科研试剂
conda virtual environment | install and list problems
Monitoring basic resources through observation cloud monitor, automatic alarm
etcd implements large-scale service governance application combat