25、数据结构/二叉树相关练习20240207

一、二叉树相关练习

请编程实现二叉树的操作

1.二叉树的创建

2.二叉树的先序遍历

3.二叉树的中序遍历

4.二叉树的后序遍历

5.二叉树各个节点度的个数

6.二叉树的深度

代码:

复制代码
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
typedef struct node//定义二叉树节点结构体
{
	int data;
	struct node *left;
	struct node *right;
}*binary;
binary create_node()//创建节点并初始化
{
	binary s=(binary)malloc(sizeof(struct node));
	if(NULL==s)
		return NULL;
	s->data=0;
	s->left=NULL;
	s->right=NULL;
	return s;
}
binary binary_tree()
{
	int element;
	printf("please enter element(end==0):");
 	scanf("%d",&element);
	if(0==element)
		return NULL;
	binary tree=create_node();
	tree->data=element;

	tree->left=binary_tree();
	tree->right=binary_tree();
	return tree;
}
void first_output(binary tree)
{
	if(tree==NULL)
		return;
	printf("%d ",tree->data);
	first_output(tree->left);
	first_output(tree->right);
}
void mid_output(binary tree)
{
	if(NULL==tree)
		return;
	mid_output(tree->left);
	printf("%d ",tree->data);
	mid_output(tree->right);
}
void last_output(binary tree)
{
	if(NULL==tree)
		return;
	last_output(tree->left);
	last_output(tree->right);
	printf("%d ",tree->data);
}
void limit_tree(binary tree,int *n0,int *n1,int *n2)
{
	if(NULL==tree)
		return;
	if(tree->left&&tree->right)
		++*n2;
	else if(!tree->left && !tree->right)
		++*n0;
	else
		++*n1;
	limit_tree(tree->left,n0,n1,n2);
	limit_tree(tree->right,n0,n1,n2);
}
int high_tree(binary tree)
{
	if(NULL==tree)
		return 0;
	int left=1+high_tree(tree->left);
	int right=1+high_tree(tree->right);
	return left>right?left:right;
}
int main(int argc, const char *argv[])
{
	binary tree=binary_tree();//创建二叉树
	
	first_output(tree);//先序遍历
	puts("");
	mid_output(tree);//中序遍历
	puts("");
	last_output(tree);//后序遍历
	puts("");

	int n0=0,n1=0,n2=0;
	limit_tree(tree,&n0,&n1,&n2);//计算各个度的节点的个数;
	printf("n0=%d,n1=%d,n2=%d\n",n0,n1,n2);

	int high=high_tree(tree);//计算二叉树深度;
	printf("the high of the binary tree is:%d\n",high);

	return 0;
}

以下图二叉树为例运行结果:

二叉树图:

运行:

相关推荐
BothSavage11 小时前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法
小林ixn11 小时前
从暴力到KMP:一道题彻底搞懂字符串匹配的前世今生
算法
烬羽13 小时前
字符串算法入门:从反转字符串到回文判断,面试不再慌
算法·面试
先吃饱再说1 天前
判断回文字符串,从一行代码到双指针优化
算法
黄敬峰1 天前
深入理解算法核心:从递归思想、数组扁平化到快速排序
算法
得物技术1 天前
从狂野代码到按目标生产:得物推荐 AI Harness 的工程化实践|AICon 演讲整理
人工智能·算法·架构
AI小老六1 天前
SkillOpt 架构拆解:把 Skill 文本当参数,用执行轨迹训练 Agent
后端·算法·ai编程
胡萝卜术2 天前
从“分数打架”到“排名投票”:为什么你的ChatBI必须用RRF?
算法·设计模式·面试