#include <iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
typedef struct TBnode
{
int data;
int ltag,rtag;
struct TBnode *lchild;
struct TBnode *rchild;
}TBnode;
TBnode* createTree()
{
TBnode *p;
int ch;
scanf("%d",&ch);
if(ch == 0) //如果到了叶子节点,接下来的左、右子树分别赋值为0
{
p = NULL;
}
else
{
p = (TBnode*)malloc(sizeof(TBnode));
p->data = ch;
// p->ltag=0;
//p->rtag=0;
p->lchild = createTree(); //递归创建左子树
p->rchild = createTree(); //递归创建右子树
}
return p;
}
void Inthread(TBnode *p,TBnode *&pre)
{
if(p!=NULL)
{
Inthread(p->lchild,pre);
if(p->lchild==NULL)
{
p->lchild=pre;
p->ltag=1;
}
if(pre!=NULL&&pre->rchild==NULL)
{
pre->rchild=p;
pre->rtag=1;
}
pre=p;
p=p->rchild;
Inthread(p,pre);
}
}
void creat(TBnode *root)
{
TBnode *pre=NULL;
if(root!=NULL)
{
Inthread(root,pre);
pre->rchild=NULL;
pre->rtag=1;
}
}
void Prethread(TBnode *p,TBnode *&pre)
{
if(p!=NULL)
{
if(p->lchild==NULL)
{
p->lchild=pre;
p->ltag=1;
}
if(pre!=NULL&&pre->rchild==NULL)
{
pre->rchild=p;
pre->rtag=1;
}
pre=p;
if(p->ltag==0)
Prethread(p->lchild,pre);
if(p->rtag==0)
p=p->rchild;
Prethread(p->rchild,pre);
}
}
void endthread(TBnode *p,TBnode *&pre)
{
if(p!=NULL)
{
endthread(p->lchild,pre);
endthread(p->lchild,pre);
if(p->lchild==NULL)
{
p->lchild=pre;
p->ltag=1;
}
if(pre!=NULL&&pre->rchild==NULL)
{
pre->rchild=p;
pre->rtag=1;
}
pre=p;
}
}
//遍历中续索引二叉树
TBnode *frist(TBnode *p)
{
while(p->ltag==0)
p=p->lchild;
return 0;
}
TBnode *next(TBnode *p)
{
if(p->rtag==0)
return frist(p->rchild);
else
return p->rchild;
}
void inorder(TBnode *root)
{
for(TBnode *p=frist(root);p!=NULL;p=next(p))
cout<<p->data;
}
void preorder(TBnode *root)//前序遍历
{
if(root!=NULL)
{
TBnode *p=root;
while(p!=NULL)
{
while(p->ltag==0)
{
cout<<p->data<<" ";
p=p->lchild;
}
cout<<p->data<<" ";
p=p->rchild;
}
}
}
int main()
{
TBnode *shu=NULL;
shu=createTree();
creat(shu);
preorder(shu);
return 0;
}