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


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

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


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


#include 
#include 
#include 
#include 
#include 

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;
    queueque;
    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);
    }
}


你可能感兴趣的:(其他oj,数据结构-各种树)