写了一个二叉树构造及中序遍历函数

// 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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值