剑指offer
print1前序遍历,判断二叉树是否合法,即与输入的二叉树是否匹配,若不匹配输出No;
print2后序遍历输出答案;
1 #include <stdio.h> 2 int idx[1001],b[1001]; 3 typedef struct node 4 { 5 struct node * lson,*rson; 6 int value; 7 }node,*root; 8 node tree[1001]; 9 root build(int l,int r) 10 { 11 int i,midx,mval=10000; 12 if(l > r)return NULL; 13 for(i=l;i<=r;i++)if(mval>b[i]){mval = b[i],midx = i;} 14 tree[midx].lson = build(l, midx-1); 15 tree[midx].rson = build(midx+1,r); 16 tree[midx].value = mval; 17 return (&tree[midx]); 18 19 } 20 int num; 21 int print1(root ROOT) 22 { 23 if(ROOT == NULL)return 0; 24 //printf("%d ",ROOT->value); 25 if(num++!=idx[ROOT->value])return -1; 26 int f1 = print1(ROOT->lson); 27 int f2 = print1(ROOT->rson); 28 return (f1<f2?f1:f2); 29 30 } 31 void print2(root ROOT) 32 { 33 if(ROOT == NULL)return; 34 print2(ROOT->lson); 35 print2(ROOT->rson); 36 printf("%d ",ROOT->value); 37 38 } 39 40 int main(int argc, const char * argv[]) 41 { 42 int n,i,a; 43 while(scanf("%d",&n)!=EOF) 44 { 45 for(i=0;i<n;i++) 46 { 47 scanf("%d",&a); 48 idx[a] = i; 49 } 50 for(i=0;i<n;i++) 51 scanf("%d",b+i); 52 root ROOT = build(0, n-1); 53 num =0; 54 if(print1(ROOT)==-1)printf("No "); 55 else 56 { 57 print2(ROOT); 58 printf(" "); 59 } 60 } 61 }