思路:先在前序序列找到根节点,然后根据根节点在中序序列找到左子树和右子树,这样便可采用递归去构建左、右子树
头文件
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