数据结构之根据前序遍历和中序遍历构建二叉树

本文介绍了如何通过前序遍历和中序遍历的序列来构建二叉树。首先在前序遍历中找到根节点,接着在中序遍历中确定左右子树的位置,进而递归构建整个二叉树结构。
摘要由CSDN通过智能技术生成

思路:先在前序序列找到根节点,然后根据根节点在中序序列找到左子树和右子树,这样便可采用递归去构建左、右子树

头文件

application.h

struct Node;
typedef struct Node *ptrToNode;
typedef struct Node *BinaryTree;
typedef int ElementType;

//根据前序遍历和中序遍历构建二叉树
BinaryTree createBinaryTreeByPreMid(ElementType *pre,ElementType *mid,int length);
//前序遍历
void midPrint(BinaryTree T);
//后序遍历
void behPrint(BinaryTree T);

具体实现

#include <stdio.h>
#include <stdlib.h>
#include "application.h"

struct Node {
	ElementType data;
	ptrToNode left;
	ptrToNode right;
};

//根据前序遍历和中序遍历递归构建二叉树
BinaryTree createBinaryTreeByPreMid(ElementType *pre, ElementType *mid,int length) {
	BinaryTree T = NULL;
	if (length == 0)
		return T;
	//根节点
	ElementType root = pre[0];
	T = (BinaryTree) malloc(sizeof(struct Node));
	T->data = root;

	int i;
	//求左子树长度
	for (i = 0; i < length; i++) {
		if (mi
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值