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

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

头文件

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 (mid[i] == root)
			break;
	}

	//构建左子树
	if (i > 0)
		T->left = createBinaryTreeByPreMid(pre + 1, mid, i);
	else
		T->left = NULL;

	//构建右子树
	if (i + 1 < length)
		T->right = createBinaryTreeByPreMid(pre + i + 1, mid + i + 1,
				length - i - 1);
	else
		T->right = NULL;

	return T;
}
//中序遍历
void midPrint(BinaryTree T) {
	if (T == NULL)
		return;
	midPrint(T->left);
	printf("%d ", T->data);
	midPrint(T->right);
}

//后序遍历
void behPrint(BinaryTree T) {
	if (T == NULL)
		return;
	behPrint(T->left);
	behPrint(T->right);
	printf("%d ", T->data);
}

测试

#include <stdio.h>
#include "application.h"
int main(){
	ElementType mid[] = {4,2,5,1,6,3,7};
	ElementType pre[] = {1,2,4,5,3,6,7};
	BinaryTree T = createBinaryTreeByPreMid(pre,mid,7);
	midPrint(T); //中序输出测试
	printf("\n");
	behPrint(T); //后续输出测试
	return 0;
}


阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页