当前位置:网站首页>408-Binary tree-preorder inorder postorder level traversal
408-Binary tree-preorder inorder postorder level traversal
2022-08-02 04:52:00 【Cat hair has almost lost cat】
存储结构
Can be sequential or chained,Basically use chains.
Sequential storage is mainly usediThe left child of the node is 2i,右孩子为2i+1.Leave it blank if you have it or not.It's okay to store a complete binary tree or a full binary tree,The storage space utilization of common trees is too low.
链式存储
typedef struct Node{
ElemType data;
Node * left; //左孩子
Node * right; //右孩子
}BTNode, *BTree;
先序中序后序层次遍历
先序:根左右
中序:左根右
后序:右根左
层次:一层一层遍历
Preorder inorder postorder recursive code
void preOrder(BTree root){
if (root != NULL)
return;
visit(root); //You can change the position of the three lines in different order.
preOrder(root->left);
preOrder(root->right);
}
Implemented using stacks and queues
//stack preorder
void preOrder(BTree root){
Stack<BTree> s;
s.push(root);
while(root != NULL || !s.empty()){
while (tmp != NULL){
tmp = tmp->left;
visit(tmp);
s.push(tmp);
}
root = s.top();
s.pop();
root = root->right;
}
}
//stack in-order
void inOrder(BTree root){
Stack<BTree> s;
s.push(root);
while(root != NULL || !s.empty()){
while (tmp != NULL){
tmp = tmp->left;
s.push(tmp);
}
root = s.top();
s.pop();
visit(root);
root = root->right;
}
}
//栈后序,来自leetcode官方.
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> res;
if (root == nullptr) {
return res;
}
stack<TreeNode *> stk;
TreeNode *prev = nullptr;
while (root != nullptr || !stk.empty()) {
while (root != nullptr) {
stk.emplace(root);
root = root->left;
}
root = stk.top();
stk.pop();
if (root->right == nullptr || root->right == prev) {
res.emplace_back(root->val);
prev = root;
root = nullptr;
} else {
stk.emplace(root);
root = root->right;
}
}
return res;
}
};
//Hierarchical traversal is implemented using queues
void levelOrder(BTree root){
Queue<BTree> q;
q.push(root);
while (!q.emtpy()){
BTree tmp = q.pop();
visit(tmp);
if (tmp->left)
q.push(tmp->left);
if (tmp->right)
q.push(tmp->right);
}
}
边栏推荐
- LL(1)文法 :解决 if-else/if-else 产生式二义性问题
- 基础IO(下):软硬链接和动静态库
- NE5532运放加法器
- 2019 - ICCV - 图像修复 Image Inpainting 论文导读《StructureFlow: Image Inpainting via Structure-aware ~~》
- 78XX 79XX多路输出电源
- Cadence allegro导出Gerber文件(制板文件)图文操作
- IDEA2021.2安装与配置(持续更新)
- GM7150,振芯科技,视频解码器,CVBS转BT656/601,QFN32,替换TVP5150/CJC5150
- 蛮力法求解凸包问题
- 功率计,物联网,智能插座电路设计【毕业设计】
猜你喜欢
随机推荐
【Arduino 连接 SD 卡模块实现数据读写】
USB HUB USB集线器电路设计
【Arduino 连接DHT11 湿度和温度传感器】
【Arduino连接GPS 模块 (NEO-6M)读取定位数据】
调试九法准则
【Popular Science Post】Detailed explanation of MDIO interface
使用批处理脚本修改hosts文件
“520” 如何正确地用代码向 ta 表白?
【科普贴】UART接口通讯协议
LT8918L LVDS转MIPI芯片技术支持资料
使用pyqt弹出消息提示框
进程(中):进程状态、进程地址空间
博达工业云与阿里云对比
【科普贴】I2C通讯协议详解——偏软件分析和逻辑分析仪实例分析
[Arduino connects the clock module to display the time on LCD1602]
list:list的介绍和模拟实现
【科普贴】I2C接口详解——偏硬件解析
【操作系统】线程安全保护机制
NSIS来自己设定快捷方式的图标
功率计,物联网,智能插座电路设计【毕业设计】









