树的基本操作

设计二叉树类,能够对二叉树进行先序、中序、后序和层序遍历,遍历的操作为输出结点的值,设计主函数,输入一棵二叉树,按先序、中序、后序、层序的遍历顺序输出结点的值。二叉树的结点数不超过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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值