二叉树的遍历程序!数据结构C语言!要能运行的!
若以下回答无法解决问题,邀请你更新回答
展开全部
#include<iostream>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -1
typedef int Status ;
typedef char TElemType;
typedef struct TreeNode{ //定义的树结点
TElemType Data;
struct TreeNode *lchild,*rchild;
}TreeNode,*Treep;
Treep CreateTree(Treep &T) //使用先序遍历优势创建
{
char ch;
// cout<<"\n请你输入你要创建的树元素:";
cin>>ch;
if(ch == '#') //若是"#",代表该节点为空
T = NULL;
else
{
T = new TreeNode; //申请空间
if(!T)
return ERROR; //空间申请失败返回错误信息
T->Data = ch; //键盘输入结点信息
CreateTree(T->lchild); //递归调用创建左子树
CreateTree(T->rchild); //递归调用创建右子树
}
return T;
}
void TreeTreaverseF(Treep T) //二叉树先序遍历
{
if(T)
{
cout<<T->Data; //输出根节点值
TreeTreaverseF(T->lchild); //递归调用输出左子树
TreeTreaverseF(T->rchild); //递归调用输出右子树
}
}
void TreeTreaverseS(Treep T) //中序遍历二叉树
{
if(T)
{
TreeTreaverseS(T->lchild); //递归调用输出左子树
cout<<T->Data; //输出左节点
TreeTreaverseS(T->rchild); //递归调用输出右子树
}
}
void TreeTreaverseT(Treep T)
{
if(T)
{
TreeTreaverseT(T->lchild); //递归调用输出左子树
TreeTreaverseT(T->rchild); //递归调用输出右子树
cout<<T->Data; //输出右节点
}
}
int main()
{
Treep T=NULL;
cout<<"\n开始创建树状结构...\n";
cout<<"\n各元素以空格隔开\n";
CreateTree(T);
cout<<"\n先序遍历输出树...\n";
TreeTreaverseF(T);
cout<<endl<<endl;
cout<<"\n中序遍历输出树...\n";
TreeTreaverseS(T);
cout<<endl<<endl;
cout<<"\n后序遍历输出树...\n";
TreeTreaverseT(T);
cout<<endl<<endl;
return 0;
}
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -1
typedef int Status ;
typedef char TElemType;
typedef struct TreeNode{ //定义的树结点
TElemType Data;
struct TreeNode *lchild,*rchild;
}TreeNode,*Treep;
Treep CreateTree(Treep &T) //使用先序遍历优势创建
{
char ch;
// cout<<"\n请你输入你要创建的树元素:";
cin>>ch;
if(ch == '#') //若是"#",代表该节点为空
T = NULL;
else
{
T = new TreeNode; //申请空间
if(!T)
return ERROR; //空间申请失败返回错误信息
T->Data = ch; //键盘输入结点信息
CreateTree(T->lchild); //递归调用创建左子树
CreateTree(T->rchild); //递归调用创建右子树
}
return T;
}
void TreeTreaverseF(Treep T) //二叉树先序遍历
{
if(T)
{
cout<<T->Data; //输出根节点值
TreeTreaverseF(T->lchild); //递归调用输出左子树
TreeTreaverseF(T->rchild); //递归调用输出右子树
}
}
void TreeTreaverseS(Treep T) //中序遍历二叉树
{
if(T)
{
TreeTreaverseS(T->lchild); //递归调用输出左子树
cout<<T->Data; //输出左节点
TreeTreaverseS(T->rchild); //递归调用输出右子树
}
}
void TreeTreaverseT(Treep T)
{
if(T)
{
TreeTreaverseT(T->lchild); //递归调用输出左子树
TreeTreaverseT(T->rchild); //递归调用输出右子树
cout<<T->Data; //输出右节点
}
}
int main()
{
Treep T=NULL;
cout<<"\n开始创建树状结构...\n";
cout<<"\n各元素以空格隔开\n";
CreateTree(T);
cout<<"\n先序遍历输出树...\n";
TreeTreaverseF(T);
cout<<endl<<endl;
cout<<"\n中序遍历输出树...\n";
TreeTreaverseS(T);
cout<<endl<<endl;
cout<<"\n后序遍历输出树...\n";
TreeTreaverseT(T);
cout<<endl<<endl;
return 0;
}
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询