您的位置:首页 > 其它

二叉树的操作之由中根和后跟序列重建二叉树

2018-04-06 12:00 288 查看
#include <iostream>
#include <vector>
#include <string>
#include <malloc.h>
#include <stdio.h>
#include <string.h>
using namespace std;
typedef struct node
{
int data;
node *lchild,*rchild;
}TreeNode,* BTree;
void Pre(BTree root)
{
if(root==NULL)
return ;
else
{
printf("%d ",root->data);
Pre(root->lchild);
Pre(root->rchild);
}
}
BTree ReBuild(int *a,int *b,int n)
{
BTree root;
root = (BTree)malloc(sizeof(TreeNode));//注意一定要先创建一个实例
root->lchild=NULL;
root->rchild=NULL;
if(n>=1)
{
root->data=b[n-1];
int i;
for(i=0;i<n&&a[i]!=b[n-1];i++);
root->lchild=ReBuild(a,b,i);
root->rchild=ReBuild(a+i+1,b+i,n-i-1);
return root;//迭代出口
}
else
return NULL;//迭代出口
}
int a[10000];
int b[10000];
int main()
{
char c;
int i=0,j=0;
int n;
while (cin >> n){
a[i++]=n;
c = cin.get();
if (c == '\n'){
break;
}
}
while (cin >> n){
b[j++]=n;
c = cin.get();
if (c == '\n')
break;
}
BTree bt;
bt=ReBuild(a,b,i);
Pre(bt);
printf("\n");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: