首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

二叉树的中序线索平添及遍历

2012-09-19 
二叉树的中序线索添加及遍历#include stdio.h#include malloc.h#define MaxSize 100typedef char Elem

二叉树的中序线索添加及遍历
#include <stdio.h>
#include <malloc.h>
#define MaxSize 100
typedef char ElemType;
typedef enum{Pointer,Thread}Pointtype;

typedef struct node 
{
ElemType data;//数据元素
struct node *lchild;//指向左孩子结点
struct node *rchild;//指向右孩子结点
Pointtype ltag,rtag;
}BTNode;


void CreateBTNode(BTNode * &b,char *str)
{
BTNode *St[MaxSize],*p=NULL;
int top=-1,k,j=0;  
char ch;
b=NULL;//建立的二叉树初始时为空
ch=str[j];
while (ch!='\0') //str未扫描完时循环
{
  switch(ch) 
{
case '(':top++;St[top]=p;k=1; break;//为左孩子结点
case ')':top--;break;
case ',':k=2; break; //为孩子结点右结点
default:p=(BTNode *)malloc(sizeof(BTNode));
p->data=ch;p->lchild=p->rchild=NULL;
if (b==NULL) //*p为二叉树的根结点
b=p;
else //已建立二叉树根结点
{
switch(k) 
{
case 1:St[top]->lchild=p;break;
case 2:St[top]->rchild=p;break;
}
}
}
j++;
ch=str[j];
}
}

BTNode *pre=NULL;
void Inorder_Thread(BTNode *b) //中序线索化递归算法
{
if(NULL!=b)
{
Inorder_Thread(b->lchild);
if(b->lchild!=NULL)
b->ltag=Pointer;
else
b->ltag=Thread;
if(NULL!=b->rchild)
b->rtag=Pointer;
else
b->rtag=Thread;
if(NULL!=pre)
{
if(Thread==pre->rtag)
pre->rchild=b;
if(Thread==b->ltag)
b->rchild=pre;
}
pre=b;
Inorder_Thread(b->rchild);
}
}



void InOrder(BTNode *b) //中序遍历递归函数
{
BTNode *p=NULL;
if(NULL!=b)
{
p=b;
while(Pointer==p->ltag)
p=p->lchild;
while(NULL!=p)
{
printf("%c",p->data);
if(Thread==p->rtag)
p=p->rchild;
else
{
p=p->rchild;
while(Pointer==p->ltag)
p=p->lchild;
}
}
}
}



void main()
{
BTNode *b,*w;
int i=0;
char a[MaxSize];
char c;
printf("请输入你所创建的树(以#结尾):\n");
while(c!='#')
{
scanf("%c",&c);
a[i]=c;
i++;
}
  CreateBTNode(b,a); 
printf("\n中序遍历序列:");
Inorder_Thread(b); 
InOrder(b);
printf("\n");

}

中序线索添加及遍历,不能输出,问题在哪里?请大神指教!!!谢谢!!!!









[解决办法]
学数据结构啊?很重要的一门课呢,加油,推荐你一本书,科学出版社的《数据结构与算法》上面有源码,我都验证过的没有错误的
[解决办法]
请把格式弄好

热点排行