C语言实现二叉树

时间:2021-10-02 10:10:23

C语言实现二叉树


代码

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>

struct Node* createnode(long);
struct Node* addnode(long,struct Node*);
void listnodes(struct Node*);
void freenodes(struct Node*);

struct Node{
long item;
int count;
struct Node* pLeft;
struct Node* pRight;
};

/**
* C语言实现的二叉树结构
* 原理分析 主要采用递归思想
*/

int main(){
long newvalue=0;
struct Node *pRoot=NULL;
int answer=0;

do{
printf("enter the node value:\n");
scanf("%ld",&newvalue);
if(pRoot==NULL)
pRoot=createnode(newvalue);
else
addnode(newvalue,pRoot);

printf("do you want to enter another? 0 is yes! 1 is stop!\n");
scanf("%d",&answer);
}while((answer==0));


printf("\nall the input value is:\n");
listnodes(pRoot);
freenodes(pRoot);

return 0;
}

struct Node* createnode(long value){
struct Node * pNode=(struct Node *)malloc(sizeof(struct Node));
pNode->item=value;
pNode->count=1;
pNode->pLeft=NULL;
pNode->pRight=NULL;

return pNode;
}

struct Node* addnode(long value,struct Node*pNode){
if(pNode==NULL)
return createnode(value);

if(pNode->item==value){
pNode->count++;
return pNode;
}

if(value<pNode->item){
if(pNode->pLeft==NULL){
pNode->pLeft=createnode(value);
return pNode->pLeft;
}else
return addnode(value,pNode->pLeft);
}else{
if(pNode->pRight==NULL){
pNode->pRight=createnode(value);
return pNode->pRight;
}else
return addnode(value,pNode->pRight);
}
}

void listnodes(struct Node*pNode){
if(pNode->pLeft!=NULL)
listnodes(pNode->pLeft);

for(int i=0;i<pNode->count;i++)
printf("%ld\n",pNode->item);

if(pNode->pRight!=NULL)
listnodes(pNode->pRight);

}

void freenodes(struct Node*pNode){
if(pNode==NULL)
return;

if(pNode->pLeft!=NULL)
freenodes(pNode->pLeft);

if(pNode->pRight!=NULL)
freenodes(pNode->pRight);

free(pNode);
}