一个二叉树的问题
已经知道二叉树的中序和后序遍历的结果.可以确定唯一的一个二叉树.我想请问,相应的算法.请给我一些提示.谢谢.
[解决办法]
数据结构上的
书上说的很清楚
前序,中序,后序,只要给出其中两个,就可以求出另一个
也就可以求出唯一的二叉树
自己找个二叉树研究就就清楚了
[解决办法]
// 已知前序遍历和中序遍历求后序遍历
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
char data;
node* left;
node* right;
};
char a[100]; //前序遍历
char b[100]; //中序遍历
node* build(char a[],char b[],int s1,int e1,int s2,int e2)
{
if(s1>e1 || s2>e2) return NULL;
node* head=new node;
head->data=a[s1];
if(s1==e1 && s2==e2)
{
head->left=NULL;
head->right=NULL;
return head;
}
// 找出根在中序遍历中的位置
int mid2=s2;
while(b[mid2]!=a[s1]) mid2++;
int mid1;
bool found;
for(mid1=s1+1;mid1<=e1;mid1++)
{
found=false;
for(int i=s2;i<mid2 && found==false;i++) if(a[mid1]==b[i])
{found=true; }
if(found==false) break;
}
head->left=build(a,b,s1+1,mid1-1,s2,mid2-1);
head->right=build(a,b,mid1,e1,mid2+1,e2);
return head;
}
// 后续遍历
void lstvisit(node* root)
{
if(root!=NULL)
{
lstvisit(root->left);
lstvisit(root->right);
printf("%c",root->data);
}
}
// 释放内存
void mydelete(node* root)
{
if(root!=NULL)
{
mydelete(root->left);
mydelete(root->right);
delete root;
}
}
int main()
{
while(1)
{
printf("输入前序序列:");
scanf("%s",a);
printf("输入中序序列:");
scanf("%s",b);
int n=strlen(a);
node* head=build(a,b,0,n-1,0,n-1);
printf("后序遍历为 :");
lstvisit(head);
printf("\n");
mydelete(head);
}
return 0;
}
[解决办法]
算法描述
例如:
前序遍历为:12345
中序遍历为:21453
由于前序遍历中的序列中第一个是1,那么1必定是二叉树的跟
所以1可以将中序遍历分为两部分
左子树的中序序列 2
右子树的中序学列 453
同样前序遍历所对应的两部分
左子树的前序序列 2
右子树的前序序列 345
那样就可以就可以将两个前序以及两个中序序列做重复的处理