您的位置:首页 > 编程语言 > C语言/C++

二叉树先中后序遍历的C++代码

2017-12-26 17:57 295 查看
马上就要数据结构考试了,会考到二叉树的遍历算法设计题,然后就自己总结了一个关于二叉树的简单算法代码。

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define MAX 100
using namespace std;
//二叉树的储存结构
typedef struct bit

{
char data;
struct bit *lchild,*rchild;

}bitnode,*bitree;
bitree createbitree(bitree t)
{
char ch;
cin>>ch;
if(ch=='#') t=0;

else
{
t=(bitnode*)malloc(sizeof(bitnode));
if(!t) exit(-2);
t->data=ch;
t->lchild=createbitree(t->lchild);
t->rchild=createbitree(t->rchild);
}
return t;
}
//二叉树的中序遍历

void inorderzhong(bitree t)
{
if(t)
{
inorderzhong(t->lchild);
cout<<t->data;
inorderzhong(t->rchild);
}
}
//二叉树的先序遍历
void inorderxian(bitree t)
{
if(t)
{
cout<<t->data;
inorderxian(t->lchild);

inorderxian(t->rchild);
}
}
//二叉树的后序遍历
void inorderhou(bitree t)
{
if(t)
{

inorderhou(t->lchild);

inorderhou(t->rchild);
cout<<t->data;
}
}
int main()
{
bitree b=0,t=0;
cout<<"构造一颗二叉树并对其进行遍历"<<endl;
cout<<"请输入构造二叉树的字符序列:";
b=createbitree(t);
if(b)
{
cout<<"先序遍历:";
inorderxian(b);
cout<<endl;
cout<<"中序遍历:";
inorderzhong (b);
cout<<endl;
cout<<"后序遍历:";
inorderhou(b);
cout<<endl;
}
else
{
cout<<"失败";
}
return 0;
}

验证过成功,这个代码通俗易懂,看上几遍后自己试着写写就可以过。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息