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

发布于:2024-07-23 ⋅ 阅读:(134) ⋅ 点赞:(0)

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

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

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

二叉树的遍历(手算)

先序遍历代码

 

 

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);//递归遍历右子树
	}
}

中序遍历代码

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);//递归遍历右子树
	}
}

后序遍历代码

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

总结:


网站公告

今日签到

点亮在社区的每一天
去签到