#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
Node *leftchild;
Node *rightchild;
};
Node* newnode(int data)
{
Node* node = (Node *)malloc(sizeof(Node));
node->data = data;
node->leftchild = node->rightchild = NULL;
return node;
}
void addnode(Node *tree, int data)
{
if(tree->data==NULL)
tree->data = data;
else
{
Node *find = tree;
while(1)
{
if(find->data - data == 0)
{
printf("already exist!");
break;
}
else if(find->data - data > 0)
{
if(find->leftchild!=NULL)
find = find->leftchild;
else
{
find->leftchild = newnode(data);
break;
}
}
else
{
if(find->rightchild!=NULL)
find = find->rightchild;
else
{
find->rightchild = newnode(data);
break;
}
}
}
}
}
void pre(Node *tree)
{
if(tree!=NULL)
{
printf("%d->",tree->data);
pre(tree->leftchild);
pre(tree->rightchild);
}
}
void in(Node *tree)
{
if(tree!=NULL)
{
in(tree->leftchild);
printf("%d->",tree->data);
in(tree->rightchild);
}
}
void post(Node *tree)
{
if(tree!=NULL)
{
post(tree->leftchild);
post(tree->rightchild);
printf("%d->",tree->data);
}
}
void deletenode(Node *tree)
{
if(tree!=NULL)
{
deletenode(tree->leftchild);
deletenode(tree->rightchild);
free(tree);
}
}
int main()
{
Node *tree = (Node *)malloc(sizeof(Node));
tree->leftchild = tree->rightchild = NULL;
tree->data = NULL;
addnode(tree,1);
addnode(tree,7);
addnode(tree,2);
addnode(tree,8);
addnode(tree,10);
addnode(tree,9);
addnode(tree,3);
addnode(tree,5);
addnode(tree,4);
addnode(tree,6);
printf("전위 : ");
pre(tree);
printf("\n중위 : ");
in(tree);
printf("\n후위 : ");
post(tree);
deletenode(tree);
return 0;
}