您的位置:首页 > 理论基础 > 数据结构算法

天梯赛 L2-011 玩转二叉树 数据结构

2016-07-08 22:48 232 查看
题目:https://www.patest.cn/contests/gplt/L2-011

题意:

给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。

输入格式:

输入第一行给出一个正整数N(<=30),是二叉树中结点的个数。第二行给出其中序遍历序列。第三行给出其前序遍历序列。数字间以空格分隔。

输出格式:

在一行中输出该树反转后的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
7
1 2 3 4 5 6 7
4 1 3 2 6 5 7

输出样例:
4 6 1 7 5 3 2

思路:依次取先序遍历中的数,可以把中序遍历分成两部分,左边是左子树,右边是右子树,不为空就递归进入,重复上述步骤

#include <bits/stdc++.h>
using namespace std;

const int N = 50;
int n;
int arr
, brr
;

struct node
{
int data;
node *lc, *rc;
node(){}
node(int data, node *lc, node *rc):data(data), lc(lc), rc(rc) {}
};

void dfs(int l, int r, int t, node* &root)
{
int flag = -1;
for(int i = l; i <= r; i++)
if(arr[i] == brr[t]) //确定先序数字在中序中的位置
{
flag = i;
break;
}
if(flag == -1) return; //没找到,说明数据不合法,题目不会出现这种情况
root = new node(arr[flag], NULL, NULL);
if(flag > l) //左子树不为空,递归进入
dfs(l, flag - 1, t + 1, root -> lc);
if(flag < r) //右子树不为空,递归进入
dfs(flag + 1, r, t + 1 + flag - l, root -> rc);
}

void bfs(node *r)
{
queue<node*> que;
que.push(r);
int crr
, k = 0;
while(! que.empty())
{
node *p = que.front(); que.pop();
crr[k++] = p ->data;
if(p -> rc != NULL) que.push(p -> rc); //镜面反转可以让右儿子先入队左儿子后入队来实现,这样简单,也可以另写一个函数来实现实现
if(p -> lc != NULL) que.push(p -> lc);
}
for(int i = 0; i < k; i++)
printf("%d%c", crr[i], i == k - 1 ? '\n': ' ');
}

int main()
{
scanf("%d", &n);
for(int i = 1; i <= n; i++)
scanf("%d", arr + i);
for(int i = 1; i <= n; i++)
scanf("%d", brr + i);
node *r;
dfs(1, n, 1, r);
bfs(r);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: