二叉树的遍历算法之 非递归算法
原理
通过模拟栈来实现
#include <iostream>
#include <stack>
#include <utility>
struct BtreeNode{
int data;
BtreeNode* left;
BtreeNode* right;
};
class Solution{
public:
前序
void inorder(BtreeNode* root){
// 申请一个栈
std::stack<std::pair<BtreeNode* , int>> st;
// 将根节点入栈
st.push(std::pair<BtreeNode* , int> {root , 0});
while(!st.empty()){
std::pair<BtreeNode* , int>temp = st.top();
st.pop();
// 如果该节点的左右节点都为nullptr 或者 int 那个数据为 1 的之间访问
if(temp.first->left == nullptr && temp.first->right == nullptr)
// 访问节点
std::cout << temp.first->data<<" ";
else if(temp.second == 1)
// 访问根节点
std::cout << temp.first->data<<" ";
else{
temp.second = 1;
if(temp.first->right != nullptr)
st.push(std::pair<BtreeNode* , int> {temp.first->right , 0});
if(temp.first->left != nullptr)
st.push(std::pair<BtreeNode* , int> {temp.first->left , 0});
st.push(temp);
}
}
}
中序
void inorder(BtreeNode* root){
// 申请一个栈
std::stack<std::pair<BtreeNode* , int>> st;
// 将根节点入栈
st.push(std::pair<BtreeNode* , int> {root , 0});
while(!st.empty()){
std::pair<BtreeNode* , int>temp = st.top();
st.pop();
// 如果该节点的左右节点都为nullptr 或者 int 那个数据为 1 的之间访问
if(temp.first->left == nullptr && temp.first->right == nullptr)
// 访问节点
std::cout << temp.first->data<<" ";
else if(temp.second == 1)
// 访问根节点
std::cout << temp.first->data<<" ";
else{
temp.second = 1;
if(temp.first->right != nullptr)
st.push(std::pair<BtreeNode* , int> {temp.first->right , 0});
st.push(temp);
if(temp.first->left != nullptr)
st.push(std::pair<BtreeNode* , int> {temp.first->left , 0});
}
}
}
后序
void inorder(BtreeNode* root){
// 申请一个栈
std::stack<std::pair<BtreeNode* , int>> st;
// 将根节点入栈
st.push(std::pair<BtreeNode* , int> {root , 0});
while(!st.empty()){
std::pair<BtreeNode* , int>temp = st.top();
st.pop();
// 如果该节点的左右节点都为nullptr 或者 int 那个数据为 1 的之间访问
if(temp.first->left == nullptr && temp.first->right == nullptr)
// 访问节点
std::cout << temp.first->data<<" ";
else if(temp.second == 1)
// 访问根节点
std::cout << temp.first->data<<" ";
else{
temp.second = 1;
st.push(temp);
if(temp.first->right != nullptr)
st.push(std::pair<BtreeNode* , int> {temp.first->right , 0});
if(temp.first->left != nullptr)
st.push(std::pair<BtreeNode* , int> {temp.first->left , 0});
}
}
}
};