树的基本操作

设计二叉树类,能够对二叉树进行先序、中序、后序和层序遍历,遍历的操作为输出结点的值,设计主函数,输入一棵二叉树,按先序、中序、后序、层序的遍历顺序输出结点的值。二叉树的结点数不超过20

#include<iostream>
#include<queue>
using namespace std;
struct Node
{
int date;
Node *rightchild;
Node *leftchild;
};
Node *creat()
{
int t;
cin>>t;
if(t==0)
return NULL;
else
{
Node *root=new Node;
root->date=t;
root->leftchild=creat();
root->rightchild=creat();
return root;
}
};
//先序 
void front(Node *root)
{
if(root==NULL) return;
else
{
cout<<root->date<<" ";
front(root->leftchild);
front(root->rightchild);
}


}
//层序 
void ceng(Node *root)
{
if(root==NULL) return;
queue <Node *>s;
s.push(root);
while(s.empty()==0)
{
Node *t = s.front();
s.pop();
cout<<t->date<<" ";
if(t->leftchild!=NULL)
s.push(t->leftchild);
if(t->rightchild!=NULL)
s.push(t->rightchild);
}
}
//中序 
void InOrder(Node *root)
{
if(root==NULL) return;
else
{
InOrder(root->leftchild);
cout<<root->date<<" ";
InOrder(root->rightchild);
}
}
//后序 
void PostOrder(Node *root)
{
if(root==NULL) return;
else
{
PostOrder(root->leftchild);
PostOrder(root->rightchild);
cout<<root->date<<" ";
}
}
int main()
{
Node *root;
root=creat();
front(root);
cout<<endl;
InOrder(root);
cout<<endl; 
PostOrder(root);
cout<<endl;
ceng(root);
cout<<endl;
return 0;
}

猜你喜欢

转载自blog.csdn.net/perception952/article/details/78425933
今日推荐