当前位置:网站首页>414-二叉树的递归遍历
414-二叉树的递归遍历
2022-06-24 09:33:00 【liufeng2023】
1、二叉树递归遍历
递归算法的三个要素:
- 确定递归函数的参数和返回值: 确定哪些参数是递归的过程中需要处理的,那么就在递归函数里加上这个参数, 并且还要明确每次递归的返回值是什么进而确定递归函数的返回类型。
- 确定终止条件: 写完了递归算法, 运行的时候,经常会遇到栈溢出的错误,就是没写终止条件或者终止条件写的不对,操作系统也是用一个栈的结构来保存每一层递归的信息,如果递归没有终止,操作系统的内存栈必然就会溢出。
- 确定终止条件: 写完了递归算法, 运行的时候,经常会遇到栈溢出的错误,就是没写终止条件或者终止条件写的不对,操作系统也是用一个栈的结构来保存每一层递归的信息,如果递归没有终止,操作系统的内存栈必然就会溢出。
前序遍历:
class Solution {
public:
void traversal(TreeNode* cur, vector<int>& vec) {
if (cur == NULL) return;
vec.push_back(cur->val); // 中
traversal(cur->left, vec); // 左
traversal(cur->right, vec); // 右
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
traversal(root, result);
return result;
}
};
中序遍历:
void traversal(TreeNode* cur, vector<int>& vec) {
if (cur == NULL) return;
traversal(cur->left, vec); // 左
vec.push_back(cur->val); // 中
traversal(cur->right, vec); // 右
}
后序遍历:
void traversal(TreeNode* cur, vector<int>& vec) {
if (cur == NULL) return;
traversal(cur->left, vec); // 左
traversal(cur->right, vec); // 右
vec.push_back(cur->val); // 中
}
边栏推荐
- LeetCode: 377. Combined sum IV
- Canvas draw picture
- 顶刊TPAMI 2022!基于不同数据模态的行为识别:最新综述
- 使用Live Chat促進業務銷售的驚人技巧
- Cicflowmeter source code analysis and modification to meet requirements
- Latex formula and table recognition
- Codeforces Round #392 (Div. 2) D. Ability To Convert
- SQL statistics of users logged in for N consecutive days
- Baidu AI template for knowledge understanding
- [Eureka source code analysis]
猜你喜欢
Thinkphp5 multi language switching project practice
vim的使用
grpc本地测试联调工具BloomRPC
Use of vim
In depth study paper reading target detection (VII) Chinese English Bilingual Edition: yolov4 optimal speed and accuracy of object detection
微信小程序学习之 实现列表渲染和条件渲染.
js单例模式
Arbre binaire partie 1
About thinkphp5, use the model save() to update the data prompt method not exist:think\db\query- & gt; Error reporting solution
How to make social media the driving force of cross-border e-commerce? This independent station tool cannot be missed!
随机推荐
谈谈数字化转型晓知识
Programming questions (continuously updated)
生产者/消费者模型
grpc本地测试联调工具BloomRPC
Seekbar with text: customize progressdrawable/thumb: solve incomplete display
ssh远程免密登录
How do novices choose the grade of investment and financial products?
【Eureka注册中心】
【自定义Endpoint 及实现原理】
js代理模式
PostgreSQL
threejs的点光源+环境光
Algorithm -- find and maximum length k subsequence (kotlin)
indexedDB本地存储,首页优化
canvas 绘制图片
Tnsnames Ora file configuration
Talking about the knowledge of digital transformation
桌面软件开发框架大赏
Dragging El table sortablejs
2021-08-17