#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
typedef struct Node Node;
// Defines a node in a binary tree string integers
struct Node {
long item;
int count;
Node *pLeft;
Node *pRight;
};
// Function prototypes
Node *create_node(long value);
Node *add_node(long value, Node *pNode);
void list_nodes(Node *pNode);
void free_nodes(Node *pNode);
// Function main - execution starts here
int main(void) {
long newvalue = 0;
Node *pRoot = NULL;
char answer = 'n';
do{
printf("Enter the node value: ");
scanf(" %ld", &newvalue);
if(!pRoot) {
pRoot = create_node(newvalue);
} else {
add_node(newvalue, pRoot);
}
printf("Do you want to enter another (y or n)? ");
scanf(" %c", &answer);
} while(tolower(answer) == 'y');
printf("The values in ascending sequence are:\n");
list_nodes(pRoot);
free_nodes(pRoot);
return 0;
}
// Create a binary tree node
Node *create_node(long value) {
Node *pNode = malloc(sizeof(Node));
pNode->item = value;
pNode->count = 1;
pNode->pLeft = pNode->pRight = NULL;
return pNode;
}
// Add a new node to the tree
Node *add_node(long value, Node *pNode) {
if(!pNode) {
return create_node(value);
}
if(value == pNode->item) {
++pNode->count;
return pNode;
}
if(value < pNode->item) {
if(!pNode->pLeft) {
pNode->pLeft = create_node(value);
return pNode->pLeft;
} else {
return add_node(value, pNode->pLeft);
}
} else {
if(!pNode->pRight) {
pNode->pRight = create_node(value);
return pNode->pRight;
} else {
add_node(value, pNode->pRight);
}
}
}
// List the node values in ascending sequence
void list_nodes(Node *pNode) {
if(pNode->pLeft)
list_nodes(pNode->pLeft);
printf("%10d x %10ld\n", pNode->count, pNode->item);
if(pNode->pRight)
list_nodes(pNode->pRight);
}
// Release memory allocated to nodes
void free_nodes(Node *pNode) {
if(!pNode)
return;
if(pNode->pLeft)
free_nodes(pNode->pLeft);
if(pNode->pRight)
free_nodes(pNode->pRight);
return free(pNode);
}
输入和输出结果
Enter the node value:
Do you want to enter another (y or n)? y
Enter the node value: 2
Do you want to enter another (y or n)? y
Enter the node value: 3
Do you want to enter another (y or n)? y
Enter the node value: 555
Do you want to enter another (y or n)? y
Enter the node value: 44
Do you want to enter another (y or n)? y
Enter the node value: 2
Do you want to enter another (y or n)? y
Enter the node value: 1
Do you want to enter another (y or n)? y
Enter the node value: 44
Do you want to enter another (y or n)? n
The values in ascending sequence are:
2 x 1
2 x 2
1 x 3
2 x 44
1 x 555