树的基本操作(C语言)
代码
#include <cstdio>
#include <cstdlib>
#include <queue>
#include <algorithm>
using namespace std;
typedef struct _btree
{
int data;
struct _btree *left;
struct _btree *right;
}btree,*ptree;
ptree BuildTree(int data[]);
void PrintTree(ptree ptr);
void CountLeaf(ptree ptr,int &count);
void leaveorderoutput(ptree ptr);
int depth(ptree ptr);
void countElem(ptree ptr,int &elem);
ptree copyTree(ptree ptr);
void DeleteTree(ptree ptr);
int main(void)
{
int array[10];
int count=0;
int countelem=0;
for(int i=0;i<10;i++)
{
array[i]=rand()%10;
}
for(int i=0;i<10;i++)
{
printf("%d ",array[i]);
}
printf("\n");
ptree root=BuildTree(array);
PrintTree(root);
printf("\n");
CountLeaf(root,count);
printf("CountLeaf:%d\n",count);
leaveorderoutput(root);
printf("\n");
int depthval=depth(root);
printf("depth:%d\n",depthval);
countElem(root,countelem);
printf("count elem:%d\n",countelem);
ptree root2=copyTree(root);
PrintTree(root2);
printf("\n");
DeleteTree(root);
DeleteTree(root2);
}
ptree BuildTree(int data[])
{
ptree root=NULL;
int i=0;
root=(ptree)malloc(sizeof(btree));
root->data=data[i++];
root->left=NULL;
root->right=NULL;
ptree ptr=root,pre;
while(i!=10)
{
ptr=root;
while(ptr != NULL)
{
pre=ptr;
if(data[i]>ptr->data)
{
ptr=ptr->left;
}
else
{
ptr=ptr->right;
}
}
ptr=(ptree)malloc(sizeof(btree));
ptr->data=data[i++];
ptr->left=NULL;
ptr->right=NULL;
if(ptr->data > pre->data)
{
pre->left=ptr;
}
else
{
pre->right=ptr;
}
}
return root;
}
void PrintTree(ptree ptr)
{
if(ptr != NULL)
{
PrintTree(ptr->left);
printf("%d ",ptr->data);
//PrintTree(ptr->left);
PrintTree(ptr->right);
}
}
void CountLeaf(ptree ptr,int &count)
{
if(ptr != NULL)
{
if(ptr->left == NULL && ptr->right == NULL)
{
++count;
}
CountLeaf(ptr->left,count);
CountLeaf(ptr->right,count);
}
}
void leaveorderoutput(ptree ptr) // 显示每层元素
{
queue<ptree> q;
ptree p;
q.push(ptr);
while(!q.empty())
{
p=q.front();
q.pop();
printf("%d ",p->data);
if(p->left != NULL)
{
q.push(p->left);
}
if(p->right != NULL)
{
q.push(p->right);
}
}
}
int depth(ptree ptr)
{
int depthLeft,depthRight,depthval;
if(ptr == NULL)
{
depthval=-1;
}
else
{
depthLeft=depth(ptr->left);
depthRight=depth(ptr->right);
depthval=1+(depthLeft>depthRight ? depthLeft:depthRight);
}
return depthval;
}
void countElem(ptree ptr,int &elem)
{
if(ptr != NULL)
{
++elem;
countElem(ptr->left,elem);
countElem(ptr->right,elem);
}
}
ptree copyTree(ptree ptr)
{
ptree newLeft,newRight,newNode;
if(ptr==NULL)
{
return NULL;
}
newLeft=copyTree(ptr->left);
newRight=copyTree(ptr->right);
newNode=(ptree)malloc(sizeof(btree));
newNode->data=ptr->data;
newNode->left=newLeft;
newNode->right=newRight;
return newNode;
}
void DeleteTree(ptree ptr)
{
if(ptr != NULL)
{
DeleteTree(ptr->left);
DeleteTree(ptr->right);
free(ptr);
}
}