题目:给定二叉树的先序和中序遍历,构建这个二叉树。例如:先序遍历结果是:abdcef,中序遍历的结果是:dbaecf,如何构建二叉树。
分析:先序遍历的结果中的每一个节点,将中序遍历的结果分为左右子树两部分,递归构建二叉树,就可以完成树得构建。
#include <stdio.h>
#include <stdlib.h>
#define N 6
typedef struct node{
char ch;
struct node *left;
struct node *right;
}*node_ptr;
char pre[]={'a','b','d','c','e','f'};
char in[]={'d','b','a','e','c','f'};
node_ptr
build_tree(int pre_start,int pre_end,int in_start,int in_end)
{
char root_value = pre[pre_start];
int pre_left_end,length,in_root;
node_ptr root = (node_ptr)malloc(sizeof(struct node));
if(root){
root->ch = root_value;
root->left = root->right = NULL;
}else
exit(1);
if(pre_start == pre_end){
if(in_start == in_end && pre[pre_start] == in[in_start])
return root;
else
exit(1);
}
in_root = in_start;
while(in_root <= in_end && in[++in_root] != root_value)
;
if(in_root == in_end && in[in_root] != root_value)
exit(1);
length = in_root - in_start;
pre_left_end = pre_start + length;
if(length > 0)
root->left = build_tree(pre_start+1,pre_left_end,in_start,in_root-1);
if(length < pre_end - pre_start)
root->right = build_tree(pre_left_end + 1,pre_end,in_root + 1,in_end);
return root;
}
void pre_print(node_ptr root){
if(root == NULL)
return;
printf("%c\n",root->ch);
pre_print(root->left);
pre_print(root->right);
}
void in_print(node_ptr root){
if(root == NULL)
return;
in_print(root->left);
printf("%c\n",root->ch);
in_print(root->right);
}
int main(){
node_ptr root = build_tree(0,N-1,0,N-1);
pre_print(root);
printf("\n");
in_print(root);
return 0;
}