gplt L2-011. 玩转二叉树(二叉树遍历)


https://www.patest.cn/contests/gplt/L2-011

题意:给你中序前序求层序镜像。


思路:根据中序前序建树,和hdu1710一样。接着层序遍历,就是bfs。不用变成镜像然后遍历,只需让右节点先进队列即可。


#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <queue>
#include <iostream>

using namespace std;

typedef long long ll;
const int N = 35;

int cnt, n;

typedef struct Tree
{
    Tree *left;
    Tree *right;
    int val;
}Tree;

Tree *root;

Tree* creat(int *preorder, int *inorder, int n)//前序、后序和子树长度
{
    Tree *tmp;
    for(int i = 0; i < n; i++)
    {
        if(preorder[0]==inorder[i])//在中序中找到这个根节点
        {
            tmp = (Tree*)malloc(sizeof(Tree));
            tmp->val = inorder[i];
            tmp->left = creat(preorder+1, inorder, i);
            tmp->right = creat(preorder+i+1, inorder+i+1, n-(i+1));
            return tmp;
        }
    }
    return NULL;
}

void levelorder(Tree *cur)
{
    cnt = 0;
    queue<Tree*>que;
    while(!que.empty()) que.pop();
    que.push(cur);
    Tree *node;
    while(!que.empty())
    {
        node = que.front();
        que.pop();
        if(cnt == n-1) printf("%d\n", node->val);
        else
        {
            printf("%d ", node->val);
            cnt++;
        }
        if(node->right != NULL) que.push(node->right);
        if(node->left != NULL) que.push(node->left);
    }
}

int main()
{
  //  freopen("in.txt", "r", stdin);
    int preorder[N], inorder[N];
    while(~scanf("%d", &n))
    {
        for(int i = 0; i < n; i++)
            scanf("%d", &inorder[i]);
        for(int i = 0; i < n; i++)
            scanf("%d", &preorder[i]);
        root = creat(preorder, inorder, n);
        levelorder(root);
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值