分别用了三种不同的方法实现了二叉树的中序遍历。
/*
input:
2
10 5 4 -1 -1 -1 20 19 -1 -1 40 -1 -1
30 10 8 20 -1 -1 -1 -1 50 40 -1 45 -1 -1 -1
output:
4 5 10 19 20 40
20 8 10 30 40 45 50
*/
#include<iostream>
#include<stack>
using namespace std;
struct BTreeNode{
//二叉树
int data;
BTreeNode *lchild;
BTreeNode *rchild;
};
struct snode{
//设置访问标识
BTreeNode *node;
bool flag;
};
/*
void InOrder(BTreeNode *t){
//递归方法
if(t == NULL)return ;
InOrder(t->lchild);
cout<<t->data<<' ';
InOrder(t->rchild);
}
*/
/*
void InOrder(BTreeNode *t){
//不断访问其左子树,然后输出其根,然后访问其接着的右子树,重复过程
stack<BTreeNode*> s;
while(!s.empty() || t != NULL){
while(t != NULL){
s.push(t);
t = t->lchild;
}
if(!s.empty()){
t = s.top();
s.pop();
cout<<t->data<<' ';
t = t->rchild;
}
}
}
*/
void InOrder(BTreeNode *t){
//按右根左的存放方式存入栈,根据栈的特性输出中序遍历。注意第一次放入的是根,第二次放入才调整其位置。
stack<snode> s;
snode temp,ltemp,rtemp;
temp.flag = false;
temp.node = t;
s.push(temp);
while(!s.empty()){
temp = s.top();
s.pop();
if(temp.flag)cout<<temp.node->data<<' ';
else{
if(temp.node->rchild != NULL){
rtemp.flag = false;
rtemp.node = temp.node->rchild;
s.push(rtemp);
}
temp.flag = true;
s.push(temp);
if(temp.node->lchild != NULL){
ltemp.flag = false;
ltemp.node = temp.node->lchild;
s.push(ltemp);
}
}
}
}
void Create(BTreeNode *&t){
//(测试用)以先序遍历构建二叉树
int x;
cin>>x;
if(x == -1)
t = NULL;
else
{
t = new BTreeNode;
t->data = x;
Create(t->lchild);
Create(t->rchild);
}
}
int main(){
BTreeNode *root = NULL;
int t;
cin>>t;
while(t--)
{
Create(root);
InOrder(root);
cout<<endl;
}
return 0;
}