码迷,mamicode.com
首页 > 其他好文 > 详细

递归创建二叉树

时间:2019-04-30 20:14:51      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:typedef   char   .com   ace   names   order   img   tno   stream   

1. 树的存储

typedef struct BiTNode
{
char data;
struct BiTNode lchild,rchild;
}BTNode,*BTree;

2 .树的创建

void CreateTree(BTree &T)
{
char ch;
cin>>ch;
if(ch==‘#‘)
{
T=NULL;
}
else
{
T=(BTree) new BTNode;
if(!T)
exit(-1);
T->data=ch;
CreateTree(T->lchild);
CreateTree(T->rchild);
}

}

3.前序遍历

void PreOrder(BTree &T)
{
if(T)
{
cout<data;
PreOrder(T->lchild);
PreOrder(T->rchild);
}
}

4.中序遍历

void PreOrder(BTree &T)
{
if(T)
{
PreOrder(T->lchild);

  cout<data;
PreOrder(T->rchild);
}
}

5.后序遍历

void PostOrder(BTree &T)
{
if(T!=NULL)
{
PostOrder(T->lchild);
PostOrder(T->rchild);
cout<data;
}
}

6. 完整代码

#include <stdlib.h>
#include
using namespace std;
typedef struct BiTNode
{
char data;
struct BiTNode lchild,rchild;
}BTNode,*BTree;
void CreateTree(BTree &T)
{
char ch;
cin>>ch;
if(ch==‘#‘)
{
T=NULL;
}
else
{
T=(BTree) new BTNode;
if(!T)
exit(-1);
T->data=ch;
CreateTree(T->lchild);
CreateTree(T->rchild);
}
}
void PreOrder(BTree &T)
{
if(T)
{
cout<data;
PreOrder(T->lchild);
PreOrder(T->rchild);
}
}
void InOrder(BTree &T)
{
if(T!=NULL)
{
InOrder(T->lchild);
cout<data;
InOrder(T->rchild);
}

void PostOrder(BTree &T)
{
if(T!=NULL)
{
PostOrder(T->lchild);
PostOrder(T->rchild);
cout<data;
}
}
int main()
{
BTree T;
cout<<"请输入树的节点:" ;
CreateTree(T);
cout<<"先序遍历:";
PreOrder(T) ;
cout<<endl;
cout<<"中序遍历:";
InOrder(T) ;
cout<<endl;
cout<<"后序遍历:";
PostOrder(T) ;
cout<<endl;
return 0;
}

7.输入样例

abd##e##cf###

8.运行截图

技术图片

递归创建二叉树

标签:typedef   char   .com   ace   names   order   img   tno   stream   

原文地址:https://www.cnblogs.com/singly/p/10797682.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!