1127. ZigZagging on a Tree (30)

#include <iostream>
#include <vector>
#include <queue>
using namespace std;

int n;
const int maxn = 31;
struct node { int data; node *l, *r;};
vector<int> post(maxn), in(maxn), ans, lnum(maxn);

node* build(int postL, int postR, int inL, int inR){//根据后序和中序建树
    if(postL > postR) return NULL;
    node *root = new node;
    root->data = post[postR];
    int k;
    for (k = inL; k <= inR; k++)
        if(in[k] == post[postR]) break;
    int numLeft = k - inL;
    root->l = build(postL, postL + numLeft - 1, inL, k - 1);
    root->r = build(postL + numLeft, postR - 1, k + 1, inR);
    return root;
}
void dfs(node *root, int depth){//求每一层的个数
    if (root == NULL) return;
    lnum[depth]++;
    if(root->l != NULL) dfs(root->l, depth + 1);
    if(root->r != NULL) dfs(root->r, depth + 1);
}
void bfs(node *root){//层序遍历的结果存在ans中
    queue<node*> q;
    q.push(root);
    while (!q.empty()) {
        node *now = q.front();
        q.pop();
        ans.push_back(now->data);
        if(now->l) q.push(now->l);
        if(now->r) q.push(now->r);
    }
}

int main(){
    cin >> n;
    for(int i = 0; i < n; i++) cin >> in[i];
    for(int i = 0; i < n; i++) cin >> post[i];
    node *root = build(0, n - 1, 0, n - 1);
    dfs(root, 0);
    bfs(root);
    //z输出
    int cnt = 0;
    printf("%d", ans[cnt++]);
    for (int i = 1; i < maxn;) {
        if (i % 2) {
            for (int j = 0; j < lnum[i]; j++)
                printf(" %d", ans[cnt+j]);
            cnt = cnt + lnum[i];
            i++;
        }else{
            for (int j = lnum[i] - 1; j >= 0; j--)
                printf(" %d", ans[cnt+j]);
            cnt = cnt + lnum[i];
            i++;
        }
    }
    cout << endl;

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值