您的位置:首页 > 理论基础 > 数据结构算法

中国大学MOOC-陈越、何钦铭-数据结构-2017秋03-树3 Tree Traversals Again(25 point(s))

2017-10-22 12:37 615 查看
题目位置

本题 提示为:使用了stack进行遍历。

我们知道使用stack 遍历的最基本思想是:

从左到右,从上到下,依次遍历。

每个节点经过三次。

根据题目所给信息可以观察出来,

通过push 我们发现 这是第一次经过每个结点(如果将其pop出,为先序遍历)

通过pop发现 这是第二次经过结点,(pop出,则为中序遍历)

题目要求给出后序遍历,通过前面的发先,我们可以很容易的找到经过第三次结点时候的位置。进而实现后序遍历。

规律为【

当pop出栈顶元素时,如果是第一次pop它,则刚刚是第二次经过。如果pop的是它上一个元素,则说明经过它到达了它上一个元素,则找到了它的第三次经过的标志。估我写出了 以下代码。



代码如下,只得了21分,不知道怎么错了,如有大神,请指点一二。

#include <stdio.h>
#include <stdlib.h>
struct Stack{
int top;
int *data;
int *flag;
}stack;
int main(){
int i,j;
int size;
int postSequence[size+2];
int num =0;
scanf("%d",&size);
stack.top=-1;
stack.data = (int*) malloc((size+2)*sizeof(int));
stack.flag = (int*) malloc((size+2)*sizeof(int));
for(i=0;i<size;i++)
{
stack.flag[i]= 0;
}
char state[10];
for(i=0;i<2*size;i++){
scanf("%s",&state);
if(strcmp(state,"Push")==0)stack.top++,scanf("%d",&stack.data[stack.top]);
else{

for(j=stack.top;j>=0;j--)
{
if(stack.flag[j] == 0){
stack.flag[j]++;
break;
}
stack.flag[j]++;
}
}
while(stack.flag[stack.top] >= 2)
{
postSequence[num] = stack.data[stack.top];
num++;
stack.flag[stack.top]=0;
stack.top--;
}
}
for(i=0;i<num;i++){
printf("%d ",postSequence[i]);
}
for(i=stack.top;i>0;i--)
{
printf("%d ",stack.data[i]);
}
printf("%d",stack.data[0]);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构 遍历
相关文章推荐