二叉树先中后序遍历的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;
}
验证过成功,这个代码通俗易懂,看上几遍后自己试着写写就可以过。
#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;
}
验证过成功,这个代码通俗易懂,看上几遍后自己试着写写就可以过。
相关文章推荐
- C++二叉树线索化并遍历的示例代码
- 二叉树的先中后序三种遍历,和先序的建立,代码详解!!
- 【数据结构】二叉树的构建及其遍历(C++实现)
- Python与C++ 遍历文件夹下的所有图片实现代码
- 数据结构与算法(C++)——二叉树的遍历
- 二叉树的先序建立与非递归遍历C++版
- 二叉树构造与遍历的C程序实现代码
- C++实现二叉树所有操作 -- 创建递归遍历迭代遍历拷贝清空查找
- 二叉树的递归与非递归遍历源码(C++)
- 二叉树的遍历方法之层序-先序-中序-后序遍历的简单讲解和代码示例
- 剑指offer刷题之c++实现的根据二叉树的前序和中序遍历重建二叉树
- c++代码实现图的BFS遍历
- 【C++】 二叉树的基本知识及其遍历
- 二叉树的各种遍历实现伪代码
- 二叉树的遍历_C++实现
- C++根据前序遍历和后序遍历建二叉树
- 二叉树的非递归前序、中序以及后序遍历C++模版类实现
- 二叉树的遍历C++实现
- 二叉树的建立与递归遍历C++版
- Windows编程 - 遍历所有进程(exe) 代码(C++)