#ifndef _TREE_H
#define _TREE_H
typedef struct _TREE
{
int data;
struct _TREE * left;
struct _TREE * right;
}TREE, * PTREE;
void init(TREE * tree);
void TreePrint(TREE * tree);
void TreePrint1(TREE * tree);
void TreePrint2(TREE * tree);
TREE * add(TREE * left, int data, TREE * right);
TREE * create(TREE * tree);
void clear(TREE * tree);
#endif
#include "Tree.h"
#include <iostream>
#include <stdlib.h>
using namespace std;
void init(TREE * tree)
{
tree->left=NULL;
tree->right=NULL;
}
void TreePrint(TREE * tree)
{
if(tree!=NULL)
{
TreePrint(tree->left);
cout<<tree->data<<" ";
TreePrint(tree->right);
}
}
void TreePrint1(TREE * tree)
{
if(tree!=NULL)
{
TreePrint(tree->left);
TreePrint(tree->right);
cout<<tree->data<<" ";
}
}
void TreePrint2(TREE * tree)
{
if(tree!=NULL)
{
cout<<tree->data<<" ";
TreePrint(tree->left);
TreePrint(tree->right);
}
}
TREE * create(TREE * tree)
{
static int count=0;
if(tree==NULL)
{
tree=(PTREE)malloc(sizeof(TREE));
tree->data=count;
tree->left=tree->right=NULL;
}
else if(count>=10)
{
tree->left=NULL;
tree->right=NULL;
return NULL;
}
else
{
tree->left=create(tree->left);
tree->right=create(tree->right);
}
count++;
return tree;
}
TREE * add(TREE * left, int data, TREE * right)
{
TREE * node;
node=(PTREE)malloc(sizeof(TREE));
node->data=data;
if(left==NULL)
node->left=NULL;
if(right==NULL)
node->right=NULL;
else
{
node->left=left;
node->right=right;
}
return node;
}
void clear(TREE * tree)
{
TREE * left;
TREE * right;
if(tree!=NULL)
{
cout<<"delete "<<tree->data<<" ";
if(tree->left!=NULL)
{
left=tree->left;
clear(left);
}
if(tree->right!=NULL)
{
right=tree->right;
clear(right);
}
free(tree);
}
}
#include "Tree.h"
#include <iostream>
using namespace std;
void main(void)
{
TREE * node;
TREE * node1;
TREE * node2;
TREE * node3;
TREE * node4;
TREE * node5;
TREE * node6;
node3=add(NULL, 12, NULL);
node4=add(NULL, 13, NULL);
node5=add(NULL, 14, NULL);
node6=add(NULL, 15, NULL);
node1=add(node3, 10, node4);
node2=add(node5, 11, node6);
node=add(node1, 9, node2);
//node->data=9;
//node->left=node1;
//node->right=node2;
TreePrint(node);
cout<<endl;
TreePrint1(node);
cout<<endl;
TreePrint2(node);
cout<<endl;
clear(node);
system("pause");
}
没用的函数大家可以忽略掉就ok了
测试结果