#include<stdio.h>
#include<stdlib.h>
#include<time.h>
struct TreeNode{
int data;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode *createNode(int num){/*创建新的树节点*/
struct TreeNode *T;
T=(struct TreeNode *)malloc(sizeof(struct TreeNode));
T->data=num;
T->left=NULL;
T->right=NULL;
return T;
}
struct TreeNode *add(struct TreeNode *T,int num){/*向树中加元素*/
if(T==NULL){
return createNode(num);
}
if(num<T->data){
T->left=add(T->left,num);
}else if(num>T->data){
T->right=add(T->right,num);
}
/*剩余一种情况为num和T->data相等,不作处理,这里构造的是没有重复元素的二叉树*/
return T;
}
void PreOrder(struct TreeNode *T){/*前序遍历*/
if(T!=NULL){
printf("\t%d",T->data);
PreOrder(T->left);
PreOrder(T->right);
}
}
void InOrder(struct TreeNode *T){/*中序遍历*/
if(T!=NULL){
InOrder(T->left);
printf("\t%d",T->data);
InOrder(T->right);
}
}
void PostOrder(struct TreeNode *T){/*后序遍历*/
if(T!=NULL){
PostOrder(T->left);
PostOrder(T->right);
printf("\t%d",T->data);
}
}
int Count(struct TreeNode *T){/*求二叉树节点数*/
if(T==NULL){
return 0;
}
return 1+Count(T->left)+Count(T->right);
}
int Count2(struct TreeNode *T){/*求二叉树中度为二的节点数*/
if(T==NULL){
return 0;
}
int rev=0;
if(T->left&&T->right){
rev++;
}
return rev+Count2(T->left)+Count2(T->right);
}
int CountLeaf(struct TreeNode *T){/*求叶节点数*/
if(T==NULL){
return 0;
}
if(T->left==NULL&&T->right==NULL){
return 1;
}else{
return CountLeaf(T->left)+CountLeaf(T->right);
}
}
int Max(int n1,int n2){
if(n1>n2){
return n1;
}
return n2;
}
int Height(struct TreeNode *T){/*二叉树的高度*/
if(T==NULL){
return 0;
}
return 1+Max(Height(T->left),Height(T->right));
}
int main(){
struct TreeNode *T;
T=NULL;
srand(time(NULL));
for(int i=0;i<12;i++){
T=add(T,rand()%40);
}
printf("前序遍历:\n");
PreOrder(T);
printf("\n中序遍历:\n");
InOrder(T);
printf("\n后序遍历:\n");
PostOrder(T);
printf("\n此二叉树节点数: %d",Count(T));
printf("\n此二叉树中度为二的节点数: %d",Count2(T));
printf("\n此二叉树叶节点数: %d",CountLeaf(T));
printf("\n此二叉树的高度: %d",Height(T));
return 0;
}
二叉树的基本操作(C语言)
最新推荐文章于 2022-05-15 16:47:05 发布