#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node* left;
struct node* right;
} Node;
typedef struct{
Node* root;
} Tree;
//先序遍历;
void preorder(Node* node){
if(node!=NULL){
printf("%d",node->data);
preorder(node->left);
preorder(node->right);
}
}
//中序遍历;
void inorder(Node* node){
if(node!=NULL){
inorder(node->left);
printf("%d",node->data);
inorder(node->right);
}
}
//后序遍历;
void postorder(Node * node){
if(node!=NULL){
postorder(node->left);
postorder(node->right);
printf("%d",node->data);
}
}
//插入,查找二叉树,这样输入的二叉树,在中序遍历的时候数据从小到大排列;
void insert(Tree* tree, int value){
Node* node=malloc(sizeof(Node));
node->data=value;
node->left=NULL;
node->right=NULL;//二叉搜索树;
if(tree->root==NULL){
tree->root=node;
}
else{
Node* temp=tree->root;
while(temp!=NULL){
if(value<temp->data){
if(temp->left==NULL){
temp->left=node;
return;
}
else{
temp=temp->left;
}
}
if(temp->data<value){
if(temp->right==NULL){
temp->right=node;
return;
}
else{
temp=temp->right;
}
}
}
}
}
//求树的高度;
int get_height(Node* node){
if(node==NULL){
return 0;
}
else{
int left_h=get_height(node->left);
int right_h=get_height(node->right);
int max=left_h;
if(right_h>left_h){
max=right_h;
}
return max+1;//递归调用用x+1来计数;
}
}
//得到最大最小值
int get_maxmum(Node* node){
if(node==NULL){
return -1;
}
else{
int m1=get_maxmum(node->left);
int m2=get_maxmum(node->right);
int m3=node->data;
int max=m1;
if(m2>max){max=m2;}
if(m3>max){max=m3;}
return max;
}
}
//求节点个数;
int countnode(Node* node){
int n1,n2;
if(node==NULL){
return 0;
}
else{
n1=countnode(node->left);
n2=countnode(node->right);
return n1+n2+1;
}
}
int main()
{
int arr[7]={6,3,8,2,5,1,7};
Tree tree;
tree.root=NULL;
for(int i=0;i<7; i++){
insert(&tree,arr[i]);
}
printf("前序遍历:");
preorder(tree.root);
printf("\n");
printf("中序遍历:");
inorder(tree.root);
printf("\n");
printf("后序遍历:");
postorder(tree.root);
printf("\n");
int h=get_height(tree.root);
printf("高度为:%d",h);
printf("\n");
int max=get_maxmum(tree.root);
printf("最大值为:%d",max);
printf("\n");
int count=countnode(tree.root);
printf("结点数为:%d",count);
printf("\n");
}
二叉树的进阶(C语言)
最新推荐文章于 2025-06-04 16:13:13 发布