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;
}

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

二叉树图:

运行:

相关推荐
wfeqhfxz25887824 小时前
YOLO13-C3k2-GhostDynamicConv烟雾检测算法实现与优化
人工智能·算法·计算机视觉
Aaron15884 小时前
基于RFSOC的数字射频存储技术应用分析
c语言·人工智能·驱动开发·算法·fpga开发·硬件工程·信号处理
Queenie_Charlie5 小时前
前缀和的前缀和
数据结构·c++·树状数组
_不会dp不改名_6 小时前
leetcode_3010 将数组分成最小总代价的子数组 I
算法·leetcode·职场和发展
你撅嘴真丑8 小时前
字符环 与 变换的矩阵
算法
早点睡觉好了8 小时前
重排序 (Re-ranking) 算法详解
算法·ai·rag
gihigo19988 小时前
基于全局自适应动态规划(GADP)的MATLAB实现方案
算法
念越8 小时前
数据结构:栈堆
java·开发语言·数据结构
dear_bi_MyOnly9 小时前
【多线程——线程状态与安全】
java·开发语言·数据结构·后端·中间件·java-ee·intellij-idea
ctyshr9 小时前
C++编译期数学计算
开发语言·c++·算法