当前位置:网站首页>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);
}
}
边栏推荐
猜你喜欢
随机推荐
IoT solution
MPU6050 accelerometer and gyroscope sensor is connected with the Arduino
GM7150,振芯科技,视频解码器,CVBS转BT656/601,QFN32,替换TVP5150/CJC5150
基于阿里云OSS+PicGo的个人图床搭建
所有子字符串中的元音 —— LeetCode - 2063
Anaconda(Jupyter)里发现不能识别自己的GPU该怎么办?
龙讯LT6911系列C/UXC/UXB/GXC/GXB芯片功能区别阐述
openwrt RK3568_EVB移植
写博客的原因。
为什么D类音频功放可以免输出滤波器
MC1496乘法器
Typora use
发布全新的配置格式 - AT
出差电子流应用实战
GM7150 CVBS转BT656视频解码芯片详细内容及设计要求
开源代码交叉编译操作流程及遇到的问题解决(lightdm)
【详解】线程池及其自定义线程池的实现
基础IO(上):文件管理和描述符
WebApp 在线编程成趋势:如何在 iPad、Matepad 上编程?
【科普贴】SPI接口详解









