#include<bits/stdc++.h>
using namespace std;
/* 1
2 3
4 5 6
7 8
*/
void pre_order(TreeNode*root){
if(root==nullptr){
return nullptr;
}
cout<<root->data<<endl;
pre_order(root->left);
pre_order(root->right);
}
void in_order(TreeNode*root){
if(root==nullptr){
return nullptr;
}
in_order(root->left);
cout<<root->data<<endl;
in_order(root->right);
}
void post_order(TreeNode*root){
if(root==nullptr){
return nullptr;
}
post_order(root->left);
post_order(root->right);
cout<<root->data<<endl;
}
void pre_order(TreeNode*root){
if(root==nullptr)
return;
stack<TreeNode>s;
TreeNode* p=root;
while(!s.empty()||p!=nullptr){
while(p){
cout<<p->data<<endl;
s.push(p);
p=p->left;
}
if(!s.empty()){
p=s.top();
s.pop();
p=p->right;
}
}
}
void in_order(TreeNode*root){
if(root==nullptr)
return;
stack<TreeNode>s;
TreeNode *p = root;
while(p!=nullptr||!s.empty()){
while(p){
s.push(p);
p=p->left;
}
if(!s.empty()){
p=s.top();
cout<<p->data<<endl;
s.pop();
p=p->right;
}
}
}
/*
两个栈s1,s2,s1负责把栈顶结点cur出栈,s2.push(s2),并在其左右儿子结点存在的情况下入栈左右儿子;
循环运行,其实s2保存的就是后序遍历的序列(只不过是反向顺序保存),挨个出栈即可;
*/
void post_order(TreeNode*root){
if(root==nullptr)
return;
stack<TreeNode>s1;
stack<TreeNode>s2;
s1.push(root);
while(!s1.empty()){
TreeNode *cur=s1.top();
s1.pop();
s2.push(cur);
if(s1->left)
s1.push(s1->left);
if(s1->right)
s1.push(s1->right);
}
while(!s2.empty()){
cout<<s2.top()->data<<endl;
s2.pop();
}
}
/*
*/
void post_order2(TreeNode*root){
if(root==nullptr)
return;
stack<TreeNode>s;
TreeNode* pre=nullptr;
s.push(root);
while(!s.empty()){
TreeNode *cur=s.top()
if((cur->left==nullptr&&cur->right==nullptr)||pre!=nullptr&&(pre==cur->left||pre==cur->right)){
cout<<cur->data<<endl;
s.pop();
pre=cur;
}else{
if(cur->right)
s.push(cur->right);
if(cur->left)
s.push(cur->left);
}
}
}
树的非递归遍历
最新推荐文章于 2021-02-16 22:35:26 发布