1020 Tree Traversals (25)(25 分)
Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (<=30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2
分析
输入 结点总数 后序 中序
输出 层次遍历
思路
层次遍历就是用队列实现,主要是怎么通过后序和中序建立一个二叉树
我的思路是倒着看后序遍历,第一个就是根节点,指针m指向上一个添加了的结点,对于一个新的结点,先判断m左右是不是已经不能有小孩了, 如果是,m指向m的父母直到可以有小孩为止,然后根据在中序中的序号比对判断是左小孩还是右小孩。这个结点归进二叉树之后,m指向它并保存其父节点的父母在中序中的序号,并把它在中序中置0
问题
1.这个算法是我自己想的,感觉很麻烦,再看看别人的思路。
2.我判断m能不能有小孩是根据中序中左右是不是0,所以内存要比30多开一个,一开始测试点5一直过不了就是因为我把中序的数组长度写的是30
代码
#include <iostream>
#include <malloc.h>
using namespace std;
typedef struct BNode{
int data;
int pf;
BNode *lchild,*rchild,*p;
}BNode;
int geti(int a[],int n,int x){
int i = -1;
for(i = 0;i<n;i++){
if(a[i] == x) return i;
}
return -1;
}
BNode* creat(BNode *b,int h[],int z[],int n){
int i,j;
int k,t;
b = (BNode *)malloc(sizeof(BNode));
b->data = h[n-1];
BNode *m = b;
t = geti(z,n,m->data);
z[t] = 0;
for(i = n-2;i>=0;i--){
k = geti(z,n,h[i]);
BNode *s = (BNode *)malloc(sizeof(BNode));
s->lchild = NULL;
s->rchild = NULL;
s->data = h[i];
while(z[t-1]==0&&z[t+1]==0){
t = m->pf;
m = m->p;
}
s->p = m;
s->pf = t;
if(k>t) m->rchild = s;
else m->lchild = s;
m = s;
t = k;
z[k] = 0;
}
return b;
}
void print(BNode *p,int n){
int f,r,k=0;
BNode *que[30];
f = 0; r = 0;
BNode *q;
if(p!=NULL){
r = (r+1)%30;
que[r] = p;
while(f!=r){
f = (f+1)%30;
q = que[f];
cout<<q->data;k++;
if(k!=n) cout<<" ";
if(q->lchild!=NULL){
r = (r+1)%30;
que[r] = q->lchild;
}
if(q->rchild!=NULL){
r = (r+1)%30;
que[r] = q->rchild;
}
}
}
}
int main(){
int num,i;
cin>>num;
int h[31],z[31]={0};
for(i = 0;i<num;i++) cin>>h[i];
for(i = 0;i<num;i++) cin>>z[i];
BNode *p = creat(p,h,z,num);
print(p,num);
return 0;
}