您的位置:首页 > 其它

根据前序和中序创建二叉树

2017-11-04 20:42 851 查看
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node* tree_pointer;
typedef struct node{
tree_pointer left_child;
tree_pointer right_child;
char data;
}tree;
int find_index(char* arr,char data);//找到对应值在数组的索引
void create_tree(tree **node,char *preorder,char *inorder);
int num;
int Index=1;//全局变量
void post_order(tree *what)
{
if (what == NULL)
return;
post_order(what->left_child);
post_order(what->right_child);
printf("%c ", what->data);
}
int main()
{
char preorder[100] = {0};
char inorder[100] = {0};
printf("输入节点个数:");
scanf(" %d",&num);
//i=1开始的好处是i=0设置了哨兵
//查中序遍历最左边元素的时候,最左边的元素向左边找的时候是空
//这才证明这个点没有左子树
printf("输入前序序列:");
for(int i=1;i<=num;i++)
scanf(" %c",&preorder[i]);
printf("输入中序序列:");
for(int i=1;i<=num;i++)
scanf(" %c",&inorder[i]);
tree *node;
create_tree(&node,preorder,inorder);
printf("后序的结果是:");
post_order(node);//后续遍历检验答案
}

void create_tree(tree **node,char *preorder,char *inorder)
{
int find_in;
(*node) = (tree *)malloc(sizeof(tree));
//前序第一个是根,所以找前序第一个,建立根节点
(*node)->data = preorder[Index];//root
find_in = find_index(inorder,preorder[Index]);
//找到该节点在序列中对应的位置
find_pre = 1;//原则就是服从先序的顺序,直至先序全部搜索结束
preorder[Index++] = '\0';
//每次创建一个节点,在数组中就把该节点删除,方便如何结束递归
//Index可以记录已经创建了多少节点了

inorder[find_in] = '\0';//将中序对应的值记为'\0
if(inorder[find_in-1]!='\0')
//如果中序列中已经创立的节点左边有数值,证明有左子树
create_tree(&((*node)->left_child),preorder,inorder);
else//没有左子树就记为空
(*node)->left_child = NULL;

if(inorder[find_in+1]!='\0')//有右子树
create_tree(&((*node)->right_child),preorder,inorder);
else//没有右子树就记为空
(*node)->right_child = NULL;
}
int find_index(char *arr,char data)
{
for(int i=1;i<=num;i++)
//切记,这里不能用strlen,因为删除一个用'\0',
//而且因为有哨兵,所以永远是0
{
if(arr[i] == data)
return i;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二叉树