PAT--ZigZagging on a Tree (30)

来源:互联网 发布:淘宝刷单处罚新规则 编辑:程序博客网 时间:2024/05/29 10:12

按照规律建树,然后判断输出。。

#include <iostream>#include <stdio.h>#include <string.h>#include <stack>#include <stdlib.h>#include <malloc.h>#include <queue>#define pre(i,n) for(int i=0;i<n;i++)#define pte(i,n) for(int i=1;i<=n;i++)const int MAX_N = 1005;const int MAX_M = 10005;using namespace std;struct node{    struct node *left;    struct node *right;    int data;};struct node* newtree(int *zhongxu,int *houxu,int l){    if(l<=0) return NULL;    node *p,*q;    p=(node*)malloc(sizeof(node));    p->data=*(houxu+l-1);    //cout<<p->data<<" "<<l<<endl;    int i;    for(i=0;i<l;i++){           // cout<<*(zhongxu+i)<<" "<<p->data<<endl;        if(*(zhongxu+i)==p->data) break;    }    //cout<<i<<endl;    //if(i>0)    p->left=newtree(zhongxu,houxu,i);    //if(l-i-1>0)    p->right=newtree(zhongxu+i+1,houxu+i,l-i-1);    return p;};int houxu[35],zhongxu[35];void travace(node *t){    int flag=1;    node *p,*q;    stack<node*>sta;    queue<node*>que;    while(!que.empty()) que.pop();    while(!sta.empty()) sta.pop();    p=t;    sta.push(p);    while(1){         while(!sta.empty()){            p=sta.top();            sta.pop();          // cout<<flag<<" "<<p->data<<endl;        if(flag%2==1){            if(flag==1) printf("%d",p->data);            else printf(" %d",p->data);            if(p->right!=NULL){                que.push(p->right);            }            if(p->left!=NULL){                que.push(p->left);            }    }    else{        printf(" %d",p->data);        if(p->left!=NULL){            que.push(p->left);        }        if(p->right!=NULL){            que.push(p->right);        }    }        }        flag++;    while(!que.empty()){        p=que.front();        que.pop();        sta.push(p);    }    if(sta.empty()&&que.empty()) break;    }}int main(){    int n;    scanf("%d",&n);    pre(i,n){        scanf("%d",&zhongxu[i]);    }    pre(i,n){        scanf("%d",&houxu[i]);    }    node *tree;    tree=newtree(zhongxu,houxu,n);        travace(tree);       return 0;}


0 0
原创粉丝点击