数据结构(5.3_1)——二叉树的先中后序遍历

先序遍历------左右------前缀表达式

中序遍历------左右------中缀表达式

后序遍历------左右------后缀表达式

二叉树的遍历(手算)

先序遍历代码

cpp 复制代码
struct ElemType
{
	int value;
};
//二叉树的结点(链式存储)
typedef struct BiTNode {
	ElemType data;//数据域
	struct BiTNode *lchild, * rchild;//左、右孩子指针
}BiTNode,*BiTree;
void visit(BiTree T) {
	if (T != NULL) { // 确保结点非空
		printf("%d ", T->data.value); // 打印结点的value
	}
}
//先序遍历
void PreOrder(BiTree T) {
	if (T != NULL) {
		visit(T);//访问根结点
		PreOrder(T->lchild);//递归遍历左子树
		PreOrder(T->rchild);//递归遍历右子树
	}
}

中序遍历代码

cpp 复制代码
struct ElemType
{
	int value;
};
//二叉树的结点(链式存储)
typedef struct BiTNode {
	ElemType data;//数据域
	struct BiTNode *lchild, * rchild;//左、右孩子指针
}BiTNode,*BiTree;
void visit(BiTree T) {
	if (T != NULL) { // 确保结点非空
		printf("%d ", T->data.value); // 打印结点的value
	}
}
//先序遍历
void PreOrder(BiTree T) {
	if (T != NULL) {
		PreOrder(T->lchild);//递归遍历左子树
		visit(T);//访问根结点
		PreOrder(T->rchild);//递归遍历右子树
	}
}

后序遍历代码

cs 复制代码
struct ElemType
{
	int value;
};
//二叉树的结点(链式存储)
typedef struct BiTNode {
	ElemType data;//数据域
	struct BiTNode *lchild, * rchild;//左、右孩子指针
}BiTNode,*BiTree;
void visit(BiTree T) {
	if (T != NULL) { // 确保结点非空
		printf("%d ", T->data.value); // 打印结点的value
	}
}
//先序遍历
void PreOrder(BiTree T) {
	if (T != NULL) {
		PreOrder(T->lchild);//递归遍历左子树
		PreOrder(T->rchild);//递归遍历右子树
		visit(T);//访问根结点
	}
}

总结:

相关推荐
风中的微尘5 小时前
39.网络流入门
开发语言·网络·c++·算法
西红柿维生素6 小时前
JVM相关总结
java·jvm·算法
ChillJavaGuy7 小时前
常见限流算法详解与对比
java·算法·限流算法
散1128 小时前
01数据结构-01背包问题
数据结构
sali-tec8 小时前
C# 基于halcon的视觉工作流-章34-环状测量
开发语言·图像处理·算法·计算机视觉·c#
消失的旧时光-19438 小时前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww8 小时前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
你怎么知道我是队长9 小时前
C语言---循环结构
c语言·开发语言·算法
艾醒9 小时前
大模型面试题剖析:RAG中的文本分割策略
人工智能·算法
苏小瀚10 小时前
[数据结构] 排序
数据结构