当前位置:网站首页>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);
}
}
边栏推荐
猜你喜欢
随机推荐
Cadence allegro导出Gerber文件(制板文件)图文操作
【详解】线程池及其自定义线程池的实现
“520” 如何正确地用代码向 ta 表白?
I2C无法访问ATEC508A加密芯片问题
开源日志库 [log4c] 使用
Anaconda(Jupyter)里发现不能识别自己的GPU该怎么办?
GM8284DD,GM8285C,GM8913,GM8914,GM8905C,GM8906C,国腾振芯LVDS类芯片
PCIE电路设计
开源代码交叉编译操作流程及遇到的问题解决(lightdm)
蛮力法求解凸包问题
出差电子流应用实战
联阳(ITE)IT66021FN:HDMI转RGB芯片 3D 资料
【plang1.4.3】语言新特性:集合
idea中创建jsp项目详细步骤
功率计,物联网,智能插座电路设计【毕业设计】
【科普贴】MDIO接口详解
【Arduino 连接 SD 卡模块实现数据读写】
所有子字符串中的元音 —— LeetCode - 2063
Comparison between Boda Industrial Cloud and Alibaba Cloud
LT9211芯片资料分享