二叉树的创建,以及递归前中后序以及层次遍历

时间:2021-01-26 19:38:29
<pre name="code" class="cpp">#include<iostream>
#include<queue>
using namespace std;


typedef char ElemType;
typedef struct Node
{
ElemType data;
struct Node *lchirld;
struct Node *rchirld;
}Node,*pNode;

void create_btree(pNode &T)
{
ElemType data;

//cin>>data;
scanf("%c",&data);
if(data==' ')
{
T=NULL;
}
else
{

T=(pNode)malloc(sizeof(Node));
if(!T)
{
cout<<"添加新节点时内存分配失败"<<endl;

}
T->data=data;
create_btree(T->lchirld);
create_btree(T->rchirld);
}


}


void visit(pNode &T,int level)
{
cout<<T->data<<"位于第"<<level<<"层"<<endl;
}

void pre_order(pNode &T,int level)
{
if(T)
{
visit(T,level);
pre_order(T->lchirld,level+1);
pre_order(T->rchirld,level+1);
}
}

void in_order(pNode &T,int level)
{

if(T)
{

in_order(T->lchirld,level+1);
visit(T,level);
in_order(T->rchirld,level+1);
}
}



void post_order(pNode &T,int level)
{
if(T)
{

post_order(T->lchirld,level+1);
post_order(T->rchirld,level+1);
visit(T,level);
}
}

//层次遍历
void level_order(pNode &T)
{
int parentSize = 1, childSize = 0;
int level=1;
pNode temp;
queue<pNode> q;
q.push(T);
cout<<"第1层为:";
do
{
temp = q.front();
cout << temp->data << " ";
q.pop();

if (temp->lchirld != NULL)
{
q.push(temp->lchirld);
childSize ++;
}
if (temp->rchirld != NULL)
{
q.push(temp->rchirld);
childSize ++;
}

parentSize--;
if (parentSize == 0)
{
level++;
parentSize = childSize;
childSize = 0;
cout << endl;
cout<<"第"<<level<<"层为:";
}

} while (!q.empty());
}
void main()
{
pNode T;
create_btree(T);
cout<<"前序遍历"<<endl;
pre_order(T,1);
cout<<"中序遍历"<<endl;
in_order(T,1);
cout<<"后续遍历"<<endl;
post_order(T,1);
cout<<"层次遍历"<<endl;
level_order(T);
system("pause");
}