#include <iostream>
using namespace std;
typedef struct bnode
{
int value;
bnode* left;
bnode* right;
}bnode;
#define MAX 7
bnode* head;
void AppendNode(bnode * bn,bnode* h);
bnode* CreateNode()
{
bnode* bn = (bnode*)malloc(sizeof(bnode));
if(bn != NULL)
{
bn->left =bn->right = NULL;
return bn;
}
else
{
cout<<”Error Malloc”<<endl;
return NULL;
}
}
int InitHead()
{
head = CreateNode();
if(head == NULL)
return false;
else
{
head->left =head->right = NULL;
return true;
}
}
void CreateTree(int a[])
{
head->value =a[0];
for(int i=1;i<MAX ;i++)
{
bnode* tree = CreateNode();
if(tree == NULL)
{
return;
}
tree->value =a[i];
AppendNode(tree,head);
}
}
void AppendNode(bnode * bn,bnode* h)
{
bnode* ptr = h;
if(ptr->left == NULL || ptr->right == NULL)
{
if(ptr->value > bn->value)
h->left = bn;
else
h->right = bn;
}
else if(ptr->value > bn->value)
{
AppendNode(bn,ptr->left);
}
else
{
AppendNode(bn,ptr->right);
}
return;
}
void PrintTree(bnode* h)
{
bnode* ptr = h;
if((ptr->left == NULL)&&(ptr->right == NULL))
{
cout<<ptr->value<<endl;
return;
}
if(ptr->left != NULL)
{
PrintTree(ptr->left);
}
cout<<ptr->value<<endl;
if(ptr->right != NULL)
{
PrintTree(ptr->right);
}
}
void CreateMirro(bnode* h)
{
bnode* ptr = h;
bnode* temp ;
//if(ptr->left != NULL || ptr->right != NULL)
{
temp = ptr->left;
ptr->left = ptr->right;
ptr->right = temp;
}
if(ptr->left != NULL)
{
CreateMirro(ptr->left);
}
if(ptr ->right != NULL)
{
CreateMirro(ptr->right);
}
return;
}
void DestoryTree(bnode* h)
{
bnode* ptr = h;
bnode *temp;
if((ptr->left == NULL)&&(ptr->right == NULL))
{
temp = ptr;
free(temp);
temp = NULL;
return;
}
if(ptr->left != NULL)
{
DestoryTree(ptr->left);
}
if(ptr->right != NULL)
{
DestoryTree(ptr->right);
}
temp = ptr;
free(temp);
temp = NULL;
}
int main()
{
int array[7]={10,6,14,4,8,12,16};
if(false == InitHead())
return -1;
CreateTree(array);
PrintTree(head);
CreateMirro(head);
PrintTree(head);
CreateMirro(head);
PrintTree(head);
DestoryTree(head);
return 0;
}