#include <stdlib.h>
#include <stdio.h>
//定义树
typedef struct node{ //树的结点
int data;
struct node* left;
struct node* right;
} Node;
typedef struct { //树根
Node* root;
} Tree;
void insert(Tree* tree, int value)//创建树
{
Node* 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;
}
else {//否则进右儿子
if (temp->right == NULL){
temp->right = node;
return;
}
else
temp = temp->right;
}
}
}
return;
}
void preorder(Node* node)//树的先序遍历
{
if (node != NULL)
{
printf("%d ",node->data);
preorder(node->left);
preorder(node->right);
}
}
void midorder(Node* node)//树的中序遍历
{
if (node != NULL)
{
midorder(node->left);
printf("%d ",node->data);
midorder(node->right);
}
}
void postorder(Node* node)//树的后序遍历
{
if (node != NULL)
{
postorder(node->left);
postorder(node->right);
printf("%d ",node->data);
}
}
// 求叶子个数
int count(Node* node){
if(node==NULL){
return 0;
}else if(node->left==NULL&&node->right==NULL){
return 1;
}else{
return count(node->left)+count(node->right);
}
}
//计算二叉树的叶子节点和
int sum=0;
int sumnode(Node* t){
if(t!=NULL){
sum+=t->data;
sumnode(t->left);
sumnode(t->right);
}
return sum;
}
//计算该节点在二叉排序树中的层次
int height=0;
int level(Node* t,int x){
if(t!=NULL){
height++;
if(t->data==x) return height;
else if(t->data<x)
level(t->right,x);
else
level(t->left,x);
}
return height;
}
//计算二叉排序树有多少层
int sumcount(Node* t){
if(t==NULL) return 0;
else{
int lheight=sumcount(t->left);
int rheight=sumcount(t->right);
if(lheight>rheight)
return lheight+1;
else
return rheight+1;
}
}
int main()
{
Tree tree;
tree.root = NULL;//创建一个空树
int n;
printf("输入n个数并创建这个树");//默认6层
scanf("%d",&n);
for (int i = 0; i < n; i++)//输入n个数并创建这个树3,8,9,4,7,2
{
int temp;
printf("开始输入节点%d\t",i+1);
scanf("%d",&temp);
insert(&tree, temp);
}
printf("先序遍历结果\t");
preorder(tree.root);//先序遍历
printf("\n");
printf("中序遍历结果\t");
midorder(tree.root);//中序遍历
printf("\n");
printf("二叉树结点之和%d\n",sumnode(tree.root));
printf("二叉树叶子结点的数目%d\n",count(tree.root));
printf("7这个数在二叉树的第%d层\n",level(tree.root,7));
printf("二叉树的高度为:%d",sumcount(tree.root));
return 0;
}
在链式存储结构建立二叉树排序树
于 2022-04-02 20:59:07 首次发布