PAT--ZigZagging on a Tree (30)

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

#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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值