当前位置:网站首页>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);
}
}
边栏推荐
猜你喜欢
随机推荐
Personal image bed construction based on Alibaba Cloud OSS+PicGo
Based on the raspberry pie smart luggage development environment set up
兼容C51与STM32的Keil5安装方法
ICN6211:MIPI DSI转RGB视频转换芯片方案介绍 看完涨知识了呢
uniCloud use
进程(下):进程控制、终止、等待、替换
AD8307对数检波器
Website development plan research
C语言教程 - 制作单位转换器
案例|工业物联网解决方案·智慧钢厂高性能安全数采
【Arduino connects SD card module to realize data reading and writing】
OneNET Studio与IoT Studio对比分析
龙芯2K1000使用nfs挂载文件系统进行使用
Anaconda(Jupyter)里发现不能识别自己的GPU该怎么办?
408-二叉树-先序中序后序层次遍历
Typora使用
Arduino lights up nixie tubes
本地数据库 sqlite3 编译和使用
WebApp 在线编程成趋势:如何在 iPad、Matepad 上编程?
网站开发方案研究


![[Arduino connected to GP2Y1014AU0F dust sensor]](/img/b4/c32dcd32bf5b9e8596af406c9177a2.png)






