作者在 2013-12-26 22:16:52 发布以下内容
#include<stdio.h>
#include<stdlib.h>
typedef struct binarytree
{
int data;
struct binarytree *lchild;
struct binarytree *parent;
struct binarytree *rchild;
}BT;
BT * init_bt()
{
BT *tree=(BT *)malloc(sizeof(BT));
tree->parent=NULL;
tree->lchild=NULL;
tree->rchild=NULL;
return tree;
}
bool insert_child(BT *p,bool leftchild,int value)
{
if(p)
{
BT *node=(BT *)malloc(sizeof(BT));
node->parent=p;
node->lchild=NULL;
node->rchild=NULL;
node->data=value;
if(leftchild) p->lchild=node;
else p->rchild=node;
}
else return false;
return true;
}
void visit(BT *p)
{
if(p) printf("%d ",p->data);
}
void pre_oder(BT *root)
{
if(root) visit(root);
if(root->lchild) pre_oder(root->lchild);
if(root->rchild) pre_oder(root->rchild);
}
void destroy_tree( BT *root)
{
if(root)
{
if(root->lchild) destroy_tree(root->lchild);
if(root->rchild) destroy_tree(root->rchild);
free(root);
}
}
int main(){
BT *root;
root=init_bt();
root->data=1;
insert_child(root,1,2);
insert_child(root,0,3);
insert_child(root->lchild,1,4);
insert_child(root->lchild,0,5);
insert_child(root->rchild,0,6);
pre_oder(root);
destroy_tree(root);
system("pause");
}