4-15 根据后序和中序遍历输出先序遍历 (15分)
本题要求根据给定的一棵二叉树的后序遍历和中序遍历结果,输出该树的先序遍历结果。
输入格式:
第一行给出正整数N(≤30),是树中结点的个数。随后两行,每行给出N个整数,分别对应后序遍历和中序遍历结果,数字间以空格分隔。题目保证输入正确对应一棵二叉树。
输出格式:
在一行中输出Preorder:以及该树的先序遍历结果。数字间有1个空格,行末不得有多余空格。
输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
Preorder: 4 1 3 2 6 5 7
AC
最新更新2022.4.17
#include<bits/stdc++.h>
using namespace std;
typedef struct TNode {
int data;
struct TNode *left;
struct TNode *right;
}*Tree,Node;
Tree createTree(int a[],int b[],int n) {
Tree t;
if(n==0) return NULL;
t=new Node;
t->data=a[n-1];//后序 左右根 根在最后面
int i;
for(i=0; i<n; i++) {
if(b[i]==a[n-1])
break;
}
t->left=createTree(a,b,i);
t->right=createTree(a+i,b+i+1,n-i-1);
return t;
}
void Print(Tree t) {
//先序序列 根左右
if(t==NULL) return ;
// if(t->left==NULL&&t->right==NULL)//这里不需要这种判断
cout<<" "<<t->data;
Print(t->left);
Print(t->right);
}
int main() {
int n;
cin>>n;
int a[n],b[n];
for(int i=0; i<n; i++) cin>>a[i];
for(int i=0; i<n; i++) cin>>b[i];
Tree t=createTree(a,b,n);
cout<<"Preorder:";
Print(t);
return 0;
}
大佬们写的模板答案。 root为当前后序的根结点下标(根据当前的中序序列可以把当前的中序分为左根右) start为当前中序序列起始位置 end为当前中序序列结束位置
#include<iostream>
#include<algorithm>
using namespace std;
typedef struct TNode {
int data;
struct TNode *left;
struct TNode *Right;
}*Tree,Node;
int a[999],b[999];
int N;
//int cnt=0;垃圾
Tree setTree(int root,int begin,int end) {
//end=begin+root
if(end<begin)
return NULL;
Tree t;
t=(Node *)malloc(sizeof(Node));
t->data=a[root];//根节点
int i;
for(i=begin; i<end; i++) {
//在中序排列中寻找根节点
if(b[i]==a[root])
break;
}
t->left=setTree(root-1-(end-i),begin,i-1);
t->Right=setTree(root-1,i+1,end);
return t;
}
void Print(Tree t) {
if(t==NULL)
return ;
//if(cnt++)每一个数字前面都有空格的,我靠,我居然这里错了。。。
cout<<" ";
cout<<t->data;
Print(t->left);
Print(t->Right);
}
int main() {
Tree t1,t2;
cin>>N;
for(int i=0; i<N; i++)
cin>>a[i];
for(int i=0; i<N; i++)
cin>>b[i];
Tree T=setTree(N-1,0,N-1);
//(int root,int begin,int end)
cout<<"Preorder:";
Print(T);
return 0;
}
。。。我写的
类似的题目
4-14 还原二叉树 (15分)
别走了,这个是正确的啊啊,一直以来我的输出都是小方块,不知道为什么,后来舍友告诉我,是不是类型不匹配,我才发现,data开始时定义成char型,我死了,我改了好久。
现在是对的了。
#include<iostream>
#include<algorithm>
using namespace std;
typedef struct TNode {
int data;
struct TNode *left;
struct TNode *Right;
}*Tree,Node;
int N;
int a[999],b[999];
Tree setTree(int *a,int *b,int len) {
if(len==0)
return NULL;
Tree t;
t=(Node *)malloc(sizeof(Node));
t->data=a[len-1];
int i;
for(i=0; i<len; i++) {
if(b[i]==a[len-1])
break;
}
t->left=setTree(a,b,i);
t->Right=setTree(a+i,b+1+i,len-i-1);
return t;
}
void Print(Tree t) {
if(t==NULL)
return ;
cout<<" ";
cout<<t->data;
Print(t->left);
Print(t->Right);
}
int main() {
cin>>N;
for(int i=0; i<N; i++)
cin>>a[i];
for(int i=0; i<N; i++)
cin>>b[i];
Tree T=setTree(a,b,N);
cout<<"Preorder:";
Print(T);
return 0;
}