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

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;
}