1086. Tree Traversals Again (25)

构造binary tree,然后后序遍历输出。

构造:记录当前结点p,若读入为Push i,则i为p的child,判断为左还是右child;若读入为Pop,则当前结点没有left child and(or) right child,然后寻找下一个right child未link的结点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <cstdio>
#include <cstring>
struct{  
  int fa,l,r;
}t[31];
int n;
int p;  //当前结点
bool first=true;
void postorder(int i){
  if(i<=0) return;
  postorder(t[i].l);
  postorder(t[i].r);
  if(first){
    printf("%d",i);
    first=false;
  }
  else printf(" %d",i);
}

int main(){
  scanf("%d",&n);
  char str[10];
  for(int i=0;i<=n;i++) t[i].l=t[i].r=0;		//初始化为0,表示没有link child
  p=0;  //头结点
  while(scanf("%s",str)!=EOF){
    if(strcmp(str,"Push")==0){
      int child;
      scanf("%d",&child);
      if(t[p].l==0) t[p].l=child;
      else t[p].r=child;
      t[child].fa=p;
      p=child;
    }
    else{  //Pop 
      if(t[p].l==0){  //当前结点的left child未link,则link为虚结点-1,当前结点不变
        t[p].l=-1;
      }
      else{        //left child 已link为虚结点或真结点
        t[p].r=-1;
        while(t[p].r) p=t[p].fa;    //寻找left child 未link的结点为当前结点
      }
    }
  }
  postorder(t[0].l);
  return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值