二叉树的建立、遍历的简单代码

          代码很简单,由于在ubuntu虚拟机下,输入一个字符 ,用getchar会收到字符+回车,不知道怎么消除,所以就简单用strcmp+静态数据i结合来给节点赋值。

          至于没有free,这个习惯真不好。but由于程序简单,在程序执行完毕后,系统会给free掉这个进程malloc出来的空间的,简单代码的话对系统没有影响,要是大型系统代码的话,就存在隐患

#include <stdio.h>
#include <malloc.h>
#include <string.h>

typedef struct BiTNode_s{
	int data;
	struct BiTNode_s *LChild;
	struct BiTNode_s *RChild;
}BiTNode;

static int i = 0;
BiTNode* CreateTree()
{
	char a[10];
	BiTNode *Tree;
	scanf("%s",a);
	if(!(strcmp("quit",a))){
		Tree = NULL;
		return Tree;
	}

	Tree = (BiTNode *)malloc(sizeof(BiTNode));
	if(!Tree){
		return Tree;
	}
	Tree->data = i++;
	Tree->LChild = CreateTree();
	Tree->RChild = CreateTree();

	return Tree;
}

int pprintf(BiTNode *Tree)
{
	if(Tree == NULL){ 
		//printf("TREE is NULL!\n");
		return 0;
	}
	printf("(");
	printf("%d",Tree->data);
	if(Tree->LChild) pprintf(Tree->LChild);
	if(Tree->RChild) pprintf(Tree->RChild);
	printf(")");

	return 0;
}

int PreOrder(BiTNode *Tree)	//前遍历
{
	if(Tree){
		printf("%4d",Tree->data);
		PreOrder(Tree->LChild);
		PreOrder(Tree->RChild);
	}
}

int MidOrder(BiTNode *Tree)	//中间遍历
{
	if(Tree){
		PreOrder(Tree->LChild);
		printf("%4d\n",Tree->data);
		PreOrder(Tree->RChild);
	}
}

int main(void)
{
	BiTNode *Tree;
	Tree = CreateTree();
	if(!Tree){
		printf("root is null!\n");
		return 0;
	}
	PreOrder(Tree);
	printf("\n");
	MidOrder(Tree);
	pprintf(Tree);
	return 0;
}



  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值