C语言--树的基本操作

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<conio.h>


#define DATATYPE int 


typedef struct _tree{


DATATYPE nodecontent;
struct _tree *leftchild;
struct _tree *rightchild;

}TREE;


typedef  TREE*   PTREE;




PTREE CrtTree(DATATYPE value)
{
PTREE proot;


proot=(PTREE)malloc(sizeof(TREE));
assert(proot);
proot->nodecontent=value;
proot->leftchild=NULL;
proot->rightchild=NULL;


return proot;
}




void InsertNode(DATATYPE value,PTREE root)
{


PTREE crrt=root;
PTREE *p=&crrt;




while(*p != NULL)
{
if(value == crrt->nodecontent)
{
printf("the same content in the tree");
exit(1);
}


if(value < crrt->nodecontent)
{
p = &crrt->leftchild;
crrt = crrt->leftchild;
}
else
{


p = &crrt->rightchild;
crrt = crrt->rightchild;


}


}


*p = CrtTree(value);


}




int FindTree(PTREE root, DATATYPE value)
{
PTREE crrt=root;


while( crrt != NULL)
{
if(value == crrt->nodecontent)
{
printf("there's this value in the tree\n");
return 1;
}
if(value < crrt->nodecontent)
{
crrt = crrt->leftchild;
}
else
{
crrt = crrt->rightchild;
}
}

printf("there's no this value in the tree\n");
return 0;


}






void PreOrder(PTREE bt)  //先序遍历
{    
     if(bt)//树不为空,则执行如下操作
     {
        printf("%d ",bt->nodecontent);
         PreOrder(bt->leftchild);
         PreOrder(bt->rightchild);
     }
     return;
}


void MidOrder(PTREE bt)  //中序遍历
{
if(bt)//树不为空,则执行如下操作
{
MidOrder(bt->leftchild); //中序遍历左子树
printf("%d ",bt->nodecontent);
MidOrder(bt->rightchild); //中序遍历右子树/
}
return;
}




void PosOrder(PTREE bt ) //后序遍历
{
if(bt)
{
PosOrder(bt->leftchild); //后序遍历左子树
PosOrder(bt->rightchild); //后序遍历右子树/
        printf("%d ",bt->nodecontent); //处理结点数据
}
return;
}








void Clear(PTREE bt) // 清空二叉树,使之变为一棵空树
{
if(bt)
{
Clear(bt->leftchild); //清空左子树
Clear(bt->rightchild);//清空右子树
free(bt);//释放当前结点所占内存
bt=NULL;
}
return;
}




int main(void)
{

int num;
char ch;
PTREE root=NULL;




printf("input tree node data\n");
scanf("%d",&num);
root = CrtTree(num);


while(1)
{
printf("do u want to continue?\n");

if( (ch = getch()) == 'y')
{
scanf("%d",&num);
InsertNode(num, root);
}
else
{


break;
}
}


printf("pre order is:\n");
PreOrder(root);
printf("\n");
printf("mid order is:\n");
MidOrder(root);
printf("\n");
printf("mid order is:\n");
PosOrder(root);
printf("\n");
Clear(root);
printf("%d",root);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值