这道题的重点和难点是计算左子树的长度,右子树的长度以及post插入的位置计算
这一次我前两者做对了,但是Post插入位置的计算在遍历右子树时把postpos=l1+l2是错的要写成postpos-1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 100
int pre[N],in[N],post[N];
int n;
struct SNode
{
int data[N];
int top;
};
typedef struct SNode*Stack;
Stack CreateStack()
{
Stack S=(Stack)malloc(sizeof(struct SNode));
S->top=-1;
return S;
}
void Push(Stack S,int data)
{
S->data[++S->top]=data;
}
int Pop(Stack S)
{
return S->data[S->top--];
}
void cal(int prepos,int inleft,int inright,int postpos)
{
if(inleft>inright)
{
return;
}
if(inleft==inright)
{
// printf("xiangdeng:pre[%d]=%d %d %d %d \n",prepos,pre[prepos],inleft,inright,postpos);
post[postpos]=pre[prepos];
return ;
}
post[postpos]=pre[prepos];
int index=0;
for(int i=inleft;i<=inright;i++)
{
if(in[i]==pre[prepos])
{
index=i;
break;
}
}
int l1=index-1-inleft;//2
int l2=inright-index;//2
// printf("传输:pre[%d]=%d index %d %d %d %d \n",prepos,pre[prepos],index,inleft,inright,postpos);
/* for(int i=0;i<n;i++)
{
printf("%d ",post[i]);
}
printf("\n");*/
cal(prepos+1,inleft,index-1,postpos-l2-1);
cal(prepos+l1+2,index+1,inright,postpos-1);
}
int main()
{
scanf("%d",&n);
char s1[20]="Push";
int index1=0;
int index2=0;
Stack S=CreateStack();
for(int i=0;i<2*n;i++)
{
char s[10];
int data;
scanf("%s",s);
if(strcmp(s,s1)==0)
{
scanf("%d",&data);
pre[index1++]=data;
Push(S,data);
}
else
{
in[index2++]=Pop(S);
}
}
cal(0,0,n-1,n-1);
for(int i=0;i<n;i++)
{
printf("%d",post[i]);
if(i!=n-1)
{
printf(" ");
}
}
return 0;
}
附题面
An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbered from 1 to 6) is traversed, the stack operations are: push(1); push(2); push(3); pop(); pop(); push(4); pop(); pop(); push(5); push(6); pop(); pop(). Then a unique binary tree (shown in Figure 1) can be generated from this sequence of operations. Your task is to give the postorder traversal sequence of this tree.
Figure 1
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (≤30) which is the total number of nodes in a tree (and hence the nodes are numbered from 1 to N). Then 2N lines follow, each describes a stack operation in the format: "Push X" where X is the index of the node being pushed onto the stack; or "Pop" meaning to pop one node from the stack.
Output Specification:
For each test case, print the postorder traversal sequence of the corresponding tree in one line. A solution is guaranteed to exist. All the numbers must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:
6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop
Sample Output:
3 4 2 6 5 1