#include <string.h>
#include <stdlib.h>
#include <stdio.h>
typedef struct BiTNode {
char data;
struct BiTNode *left;
struct BiTNode *right;
}BiTNode,*BiTree;
//在中序遍历中找到根节点的位置
int find(char root_data,char *inOrder,int in_start,int in_end) {
for (int i = in_start; i <= in_end; i++)
if (inOrder[i] == root_data)
return i;
}
//根据前序遍历和中序遍历构造二叉树
BiTree buildTree1(char *preOrder,int pre_start,int pre_end,char *inOrder,int in_start,int in_end) {
if (in_start > in_end)
return NULL;
BiTree root = (BiTree)malloc(sizeof(BiTNode));
root->data = preOrder[pre_start];
root->left = NULL;
root->right = NULL;
if (in_start == in_end)
return root;
else {
int root_index = find(root->data, inOrder, in_start, in_end);
root->left = buildTree1(preOrder, pre_start + 1, pre_start + root_index - in_start, inOrder, in_start, root_index - 1);
root->right = buildTree1(preOrder, pre_start + root_index - in_start + 1, pre_end, inOrder, root_index + 1, in_end);
return root;
}
}
//根据后序遍历和中序遍历构造二叉树
BiTree buildTree2(char *inOrder,int in_start,int in_end,char *postOrder,int post_start,int post_end) {
if (in_start > in_end)
return NULL;
BiTree root = (BiTree)malloc(sizeof(BiTNode));
root->data = postOrder[post_end];
root->left = NULL;
root->right = NULL;
if (in_start == in_end)
return root;
else {
int root_index = find(root->data, inOrder, in_start, in_end);
root->left = buildTree2(inOrder, in_start, root_index - 1, postOrder, post_start, post_start + root_index - in_start - 1);
root->right = buildTree2(inOrder, root_index + 1, in_end, postOrder, post_start + root_index - in_start, post_end - 1);
return root;
}
}
构造二叉树(前序+中序&&中序+后序)
最新推荐文章于 2023-10-20 20:27:52 发布