#include<stdio.h>
#include<stdlib.h>
int num = 0;
int num1 = 0;
typedef int ElemType;
typedef struct BiTree{
ElemType data;
struct BiTree *lchild;
struct BiTree *rchild;
}BiTree;
//前序创建
void for_create_tree(BiTree **t){
int n;
scanf("%d",&n);
if(n == -1){
(*t) = NULL;
}else{
(*t) = (BiTree *)malloc(sizeof(BiTree));
(*t)->data = n;
printf("请输入%d的左子树\n",(*t)->data);
for_create_tree(&((*t)->lchild));
printf("请输入%d的右子树\n",(*t)->data);
for_create_tree(&((*t)->rchild));
}
}
//前序遍历
void for_tvs_tree(BiTree *t){
if(t!=NULL)
{
printf("%d ",t->data);
for_tvs_tree(t->lchild);
for_tvs_tree(t->rchild);
num++;
}
}
//中序遍历
void mid_tvs_tree(BiTree *t){
if(t!=NULL)
{
mid_tvs_tree(t->lchild);
printf("%d ",t->data);
mid_tvs_tree(t->rchild);
}
}
//后序遍历
void aft_tvs_tree(BiTree *t){
if(t!=NULL)
{
aft_tvs_tree(t->lchild);
aft_tvs_tree(t->rchild);
printf("%d ",t->data);
}
}
//前序打印二叉树叶子节点
void for_print_leaf(BiTree *t){
if(t!=NULL)
{
if(t->lchild==NULL&&t->rchild==NULL){
printf("%d ",t->data);
num1++;
}
for_print_leaf(t->lchild);
for_print_leaf(t->rchild);
}
}
int judge_tree_depth(BiTree *t) //后序遍历求二叉树的高度递归算法
{
int hl,hr,max;
if(t!=NULL)
{
hl=judge_tree_depth(t->lchild); //求左子树的深度
hr=judge_tree_depth(t->rchild); //求右子树的深度
max=hl>hr?hl:hr; // 得到左、右子树深度较大者
return(max+1); // 返回树的深度
}
else return(0); // 如果是空树,则返回0
}
//主函数
int main(){
BiTree *t;
printf("请输入你想创建的树元素以-1结尾\n");
for_create_tree(&t);
printf("前序遍历:");
for_tvs_tree(t);
printf("\n");
printf("中序遍历:");
mid_tvs_tree(t);
printf("\n");
printf("后序遍历:");
aft_tvs_tree(t);
printf("\n");
printf("该树的深度为%d\n",judge_tree_depth(t));
printf("该二叉树共有%d个结点\n",num);
printf("该树的叶子结点为\n");
for_print_leaf(t);
printf("\n");
printf("该二叉树共有%d个叶子节点\n",num1);
return 0;
}
二叉树的链式存储
于 2022-11-03 13:29:32 首次发布