将树转化为二叉树
来源:互联网 发布:python snmp trap 编辑:程序博客网 时间:2024/04/27 22:47
通过前面的学习,现在我们应该有能力写一些比较简单的程序了,这里的树转化为二叉树的程序就是本人自己动手写的,相信各位童鞋在学习了前面的知识之后也能够写出这个程序了,具体的实现很简单,只是将二叉树和树的初始化放到一起就可以得到结果了,这里,我选择的建立树的输入为:1 2 5 0 6 0 0 3 7 0 0 4 8 0 0 0 0 得到的结果为1 2 5 6 3 7 4 8,所有的遍历都是基于前序遍历实现
#include <iostream>
using namespace std;typedef int SElemType;
typedef int TElemType;
typedef struct BiTNode
{
TElemType data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
typedef struct CSNode
{
SElemType data;
struct CSNode *firstchild,*nextsibiling;
}CSNode,*CSTree;
bool InitTree(BiTree &T)//初始化二叉树
{
TElemType s;
cin>>s;
if(s==0) T=NULL;
else
{
if(!(T=(BiTNode *)malloc(sizeof(BiTNode)))) return 0;
T->data=s;//初始化二叉树的时候首先从根节点开始,然后在对左子树赋值,再对右子树赋值
InitTree(T->lchild);//左子树赋值
InitTree(T->rchild);//右子树赋值
}
return 1;
}
bool InitCSTree(CSTree &T)//初始化树的操作
{
SElemType s;
cin>>s;
if(s==0) T=NULL;
else
{
if(!(T=(CSTree)malloc(sizeof(CSNode)))) return 0;
T->data=s;
InitCSTree(T->firstchild);
InitCSTree(T->nextsibiling);
}
return 1;
}
bool QTraverse(CSTree T)//前序遍历树的操作
{
CSTree p;
p=T;
if(p==NULL) return 0;
else
{
cout<<p->data<<" ";
QTraverse(p->firstchild);
QTraverse(p->nextsibiling);
}
return 1;
}
bool StoTree(BiTree &T,CSTree C)//将森林转化成二叉树
{
CSTree p;
p=C;
if(p==NULL)
{
T=NULL;
return 0;
}
else
{
if(!(T=(BiTNode *)malloc(sizeof(BiTNode)))) return 0;
T->data=p->data;
StoTree(T->lchild,p->firstchild);
StoTree(T->rchild,p->nextsibiling);
}
return 1;
}
bool QTraverse(BiTree T)//前序遍历二叉树
{
if(T==NULL) return 0;
else
{
cout<<T->data<<" ";
QTraverse(T->lchild);
QTraverse(T->rchild);
}
return 1;
}
int main()
{
CSTree tree;
BiTree bitree;
InitCSTree(tree);
cout<<"树遍历的结果为:"<<endl;
QTraverse(tree);
cout<<endl;
StoTree(bitree,tree);
cout<<"已经将树转化为二叉树,下面是二叉树遍历的结果:"<<endl;
QTraverse(bitree);
cout<<"\n可以看到两个前序遍历的结果是一致的……"<<endl;
return 0;
}
- 将树转化为二叉树
- 将树转化为二叉树表示
- 将树转化为二叉树表示
- 将有序数组转化为二叉树
- 将表达式转化为二叉树
- java 将数组转化为 二叉树
- 如何将普通树转化为二叉树?
- C语言 将二叉树转化为数组
- 将二叉树转化为双向链表
- 将升序数组转化为平衡二叉树
- 面试题怎么将二叉树转化为链表
- 将有序表转化为二叉搜索树
- 将二叉搜索树转化为双向链表
- 将搜索二叉树转化为双向链表
- 将有序单链表转化为平衡二叉树
- 将二叉搜索树转化为双向链表
- 二叉树转化为双链表
- 数组转化为二叉树
- inux 禁用ipv6
- ibatis中$与#的区别
- Myeclipse添加注释模板
- 命令在win8上安装.NET3.5
- ASP.NET中Repeater控件实现分页功能
- 将树转化为二叉树
- 流布式布局
- 硬解码软解码
- ORA-29786: SIHA attribute GET failed with Error If 11gR2 ASM instance is created manually [ID 976075
- IIS6下.net伪静态html图文教程
- java当前时间精确到毫秒
- 几种常见浏览器的内核分析
- IOS 面试题
- 伦敦奥运引燃媒体大战 新媒体一枝独秀笑冠全场