原题
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
结尾无空行
答案
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 31
int Postorder[MAXSIZE]={0};
int InOrder[MAXSIZE]={0};
int N=0;
typedef struct Node* PtrNode;
typedef struct Node{
int data;
PtrNode left;
PtrNode right;
}Node;
typedef PtrNode Tree;
int findx(int x){
int i=0;
for(i=0;i<N;i++){
if(InOrder[i]==x)break;
}
return i;
}
void Read(){
int i;
for(i=0;i<N;i++){
scanf("%d",&Postorder[i]);
}
for(i=0;i<N;i++){
scanf("%d",&InOrder[i]);
}
}
Tree FindRoot(int PL,int PR,int IL,int IR){
Tree root=(PtrNode)malloc(sizeof(Node));
root->data=Postorder[PR];
root->left=NULL;
root->right=NULL;
int seat=findx(root->data);
int gap1=seat-IL;
int gap2=IR-seat;
if(gap1>0)root->left=FindRoot(PL,PL+gap1-1,IL,seat-1);
if(gap2>0)root->right=FindRoot(PR-gap2,PR-1,seat+1,IR);
return root;
}
int main(){
scanf("%d",&N);
Read();
Tree head=FindRoot(0,N-1,0,N-1);
Tree stack[N];
int LevelOrder[N];
stack[0]=head;
int front=0;
int rear=1;
while(rear<N){
if(stack[front]->left)stack[rear++]=stack[front]->left;
if(stack[front]->right)stack[rear++]=stack[front]->right;
front++;
}
int i;
printf("%d",stack[0]->data);
for(i=1;i<N;i++){
printf(" %d",stack[i]->data);
}
return 0;
}
中序+后序——>可以确定一个二叉树
后序遍历的最后一个结点数字就是每棵树的Root,在中序遍历找到这个root后,就可以区分哪些数字是左子树,哪些是右子树,中序:左+根+右,按照这个思路遍历即可。
用到了:递归+堆栈(层序遍历)