// BTree.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include"stdlib.h"
#include"malloc.h"
#define BT BTreeNode
#define MS 10
typedef struct BT{
char data;
struct BT *left;
struct BT *right;
}BT;
void CreateBTree(BT * * bt,char *a){
BT *p;
BT *s[MS];
int top = -1;
int k;
int i = 0;
*bt = NULL;
while (a[i]){
switch(a[i]){
case ' ':
break;
case '(':
if(top == MS-1){printf("栈空间太小,需要增加MS的值!\n");exit(1);}
top++;s[top]=p;k=1;break;
case')':
if(top == -1){printf("二叉树广义表字符串有错!\n");exit(1);}
top--;break;
case',':
k=2;break;
default:
if((a[i]>='a'&&a[i]<='z')||(a[i]>='A'&&a[i]<='Z')){
p = (BT*)malloc(sizeof(BT));
p->data=a[i];p->left=p->right=NULL;
if(*bt==NULL)*bt=p;
else{if(k==1)s[top]->left=p;
else s[top]->right=p;}
}
else{printf("二叉树广义表字符串错!\n");exit(1);}
}
i++;
}
}
void InitBTree(BT**bt){
*bt = NULL;
}
void Inorder(BT*bt){
if(bt!=NULL){
Inorder(bt->left);
printf("%c\n\7",bt->data);
Inorder(bt->right);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
char *ch="A(B(C),D(E(F,G),H(,I)))";
BT *p;
InitBTree(&p);
CreateBTree(&p,ch);
Inorder(p);
//printf("%d",sizeof(BT));
return 0;
}
写了一个二叉树构造及中序遍历函数
最新推荐文章于 2024-05-20 17:13:48 发布