数据结构(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);//访问根结点
	}
}

总结:

相关推荐
冰清-小魔鱼10 分钟前
各类数据存储结构总结
开发语言·数据结构·数据库
小六子成长记1 小时前
【C++】:搜索二叉树的模拟实现
数据结构·c++·算法
汉克老师1 小时前
GESP2025年9月认证C++二级真题与解析(编程题1(优美的数字))
c++·算法·整除·枚举算法·求余·拆数
Zevalin爱灰灰2 小时前
现代控制理论——第二章 系统状态空间表达式的解
线性代数·算法·现代控制
菜鸟233号2 小时前
力扣377 组合总和 Ⅳ java实现
java·数据结构·算法·leetcode
我是大咖2 小时前
二级指针与指针数组搭配
c语言·数据结构·算法
葫三生3 小时前
三生原理范畴语法表明中国哲学可为算法母语
人工智能·深度学习·算法·transformer
D_FW3 小时前
数据结构第五章:树与二叉树
数据结构·算法
WHS-_-20223 小时前
Tx and Rx IQ Imbalance Compensation for JCAS in 5G NR
javascript·算法·5g
余瑜鱼鱼鱼3 小时前
Java数据结构:从入门到精通(九)
数据结构