当前位置:网站首页>[middle order traversal of binary tree based on stack] middle order traversal of binary tree + stack, spatial complexity of O (H)
[middle order traversal of binary tree based on stack] middle order traversal of binary tree + stack, spatial complexity of O (H)
2022-06-21 06:38:00 【Grapefruit Roo】
【 Stack based traversal in binary tree 】 Middle order traversal of binary trees + Stack ,O(h) Time complexity of
In general, we usually use the recursive algorithm to traverse the binary tree , The template is as follows :
void dfs(TreeNode *root){
if(!root)return;
dfs(root->left);
cout<<root->val<<endl;
dfs(root->right);
}
The time complexity of the algorithm is O(n), If random access to binary tree is required , You need to use an array to flatten the binary tree , The space complexity is O(n)
stay Leetcode The finger of the sword offer in , Learned a binary tree in order to traverse the algorithm , The algorithm combines the data structure of stack , Reduce space complexity to O(h),h Is the height of the binary tree .
The specific algorithm is as follows :
int dfs(){
while(!cur){
sta.push(root);
root = root->left;
}
cur = sta.top();
int res = cur->val;
cur = cur->right;
return res;
}
Then the algorithm can realize that for a given binary tree, the algorithm can return a middle order traversal value every time it is called .
边栏推荐
- [graduation season] a brief talk on the learning experience before sophomore year
- delphi10 ftp文件名乱码问题
- 第12期:Spark零基础学习路线
- My college entrance examination experience and summary
- Data visualization practice: data processing
- Innovation project training: Data crawling
- Idea usage record
- 155-Solana存储数组
- [data mining] final review Chapter 5
- 机器学习之数据归一化(Feature Scaling)
猜你喜欢

不给糖就捣蛋svg万圣节js特效

Issue 6: which mainstream programming language should college students choose

Part 4: JVM memory model from the perspective of hardware / source code
Butler-Volmer 公式的由来

Modbus Poll v9.9.2 Build 1690 Modbus测试工具单文件版

C语言课程设计|学生成绩管理系统(含完整代码)

NOP法破解简易登录系统
![[[graduation season · advanced technology Er] - experience shared by senior students](/img/15/720dac05ebba3ead1b82b15f15daa6.png)
[[graduation season · advanced technology Er] - experience shared by senior students

Record the problem that Navicat connection PostgreSQL cannot display the corresponding table

麦克风loading动画效果
随机推荐
数据可视化实战:数据处理
【笔记自用】myeclipse连接MySQL数据库详细步骤
Binding method of remote data in the combox drop-down list of easyUI
Are you sure about this filter?
如何限制内网网速
827. 最大人工岛 并查集
笔记 How Powerful are Spectral Graph Neural Networks
PyG教程(5):剖析GNN中的消息传播机制
第7期:内卷和躺平,你怎么选
Sqlmap command Encyclopedia
Mysql database foundation: sub query
PyG教程(4):自定义数据集
创新项目实训:数据分析与可视化
Markdown数学语法【详细总结】
Idea usage record
[graduation season] a brief talk on the learning experience before sophomore year
出现ConcurrentModificationException这个异常报错,怎么处理?
Required Integer parameter ‘XXX‘ is not present
Is today's mathematics too cumbersome?
糖果隧道js特效代码