当前位置:网站首页>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
边栏推荐
- 解析掌握现代化少儿编程实操能力
- Expert advice | How to formulate a growth strategy for survival in an economic downturn
- Build your own image search system (1): 10 lines of code to search images by image
- In the past six months, I have done those things about the automatic return of the transaction link...
- 使用IDEA连接mysql
- 探索创客教育在线管理实施体系
- Private domain growth | Private domain members: 15 case collections from 9 major chain industries
- LeetCode_474_ one and zero
- Experience Sharing | Tips for Writing Easy-to-Use Online Product Manuals
- JMeter tutorial (a)
猜你喜欢
随机推荐
Monitoring basic resources through observation cloud monitor, automatic alarm
软件开发模式有哪些(软件工程开发模式)
Briefly talk about K-means clustering
PEG-siRNA-PCL|siRNA-PEG-LHRH|MPEG-siRNA 甲氧基聚乙二醇修饰核酸
荣耀的野望:智慧世界的“高端平民”
LeetCode_474_一和零
ACM study book introduction
JMeter tutorial (a)
ESP8266-Arduino programming example-I2C device address scan
Data visualization ---- web page displays temperature and humidity
RNA修饰质谱检测|dextran-siRNA 葡聚糖化学偶联DNA/RNA|siRNA-PLGA聚乳酸-羟基乙酸共聚物修饰核糖核酸
从专业角度分析国内创客教育发展
JUC Concurrent Programming Basics AQS
Sasser virus source code (ransomware source code)
荧光量子点修饰siRNA-QDs|纳米金修饰siRNA-Au(RNA修饰方式方法)
JMeter使用教程(二)
指定宽度截取字符串
Thesis writing strategy | how to write an academic research paper
Internship: use easypoi to import and export excel table data
GalNAc-siRNA甘露糖/半乳糖修饰脱氧核糖核酸|siRNA-S-S-DSPE(RNA修饰技术介绍)
![[GXYCTF2019]禁止套娃](/img/91/3f64bebd13a8b13fbb387c2acf8618.png)








