1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
|
/* implement tree structure
insert duplicate numbers
*/
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
struct nodetype
{
int data;
struct nodetype *left, *right;
};
typedef struct nodetype node;
node* treeinsert(node*, int);
node* newnode(int);
void treeinorder(node*);
node* newnode(int x)
{
node *p;
p = new(node);
p->data = x;
p->left = NULL;
p->right = NULL;
return (p);
}
node* treeinsert(node *root, int x)
{
if (root == NULL)
root = newnode(x);
else
if (root->data >= x) // insert at left subtree
root->left = treeinsert(root->left, x);
else // insert at right subtree
root->right = treeinsert(root->right, x);
return (root);
}
void treeinorder(node *root)
{
if (root != NULL)
{
treeinorder(root->left);
printf("%d ", root->data);
treeinorder(root->right);
}
}
void main(void)
{
int num;
node *root;
root = NULL;
printf("Enter a number to be inserted or 0 to exit: ");
scanf("%d", &num);
while (num != 0)
{
root = treeinsert(root,num);
printf("Enter a number to be inserted or 0 to exit: ");
scanf("%d", &num);
}
treeinorder(root);
printf("\n");
getch();
} |
Partager