原码如下:
//Program 11.7 Sorting integers using a binary tree
#include
#include
#include
//Function prototypes
struct Node *createnode(long value);
struct Node *addnode(long value,struct Node *pNode);
void listnodes(struct Node *pNode);
void freenodes(struct Node *pNode);
//Defines a node in a binary tree sotring integers
struct Node
{
long item;
int count;
struct Node *pLeft;
struct Node *pRight;
};
//Function main-execution starts here
int main(void)
{
long newvalue=0;
struct Node *pRoot=NULL;
char answer='n';
do
{
printf("Enter the node value:");
scanf("%ld",&newvalue);
if(pRoot==NULL)
pRoot=createnode(newvalue);
else
addnode(newvalue,pRoot);
printf("\nDo you want to enter another(y or n)?");
while(answer=getchar())
if(tolower(answer)=='y'||tolower(answer)=='n')break;
} while(tolower(answer)=='y');
printf("The value in ascending sequence are:");
listnodes(pRoot); //Output the contents of the tree
freenodes(pRoot); //Release the heap memory
return 0;
}
struct Node *createnode(long value)
{
struct Node *pNode=(struct Node *)malloc(sizeof(struct Node));
pNode->item=value;
pNode->count=1;
pNode->pLeft=pNode->pRight=NULL;
return pNode;
}
//add a new node to the tree
struct Node *addnode(long value,struct Node *pNode)
{
if(pNode==NULL)
return createnode(value);
if(value==pNode->item)
{
++pNode->count;
return pNode;
}
if(valueitem)
{
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);
}
}
//List the node values in ascending sequence
void listnodes(struct Node *pNode)
{
int i=0;
if(pNode->pLeft!=NULL)
listnodes(pNode->pLeft);
for(i=0;icount;i++)
printf("%10ld\t",pNode->item);
if(pNode->pRight!=NULL)
listnodes(pNode->pRight);
}
//Release memory allocated to nodes
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);
}
以下函数理解:
//List the node values in ascending sequence
void listnodes(struct Node *pNode)
{
int i=0;
if(pNode->pLeft!=NULL)
listnodes(pNode->pLeft);
for(i=0;icount;i++)
printf("%10ld\t",pNode->item);
if(pNode->pRight!=NULL)
listnodes(pNode->pRight);
}
当输入:56、33、77、-10、100、-5、200
输入结果为:-10、-5、33、56、77、100、200
疑问点:
输出-10、-5我能理解;第二次输入后就不能理解了
是否当遍历树过程pNode->pRight==NULL&&pNode->pLeft==NULL下次执行
节点是否会移到上一层??
请帮忙解答一下谢谢!!