思路:
这是一道关于二叉树确定以及遍历的题目。首先我们要了解前序中序的特点。
前序:根节点->左节点->右节点
中序:左节点->根结点->右节点
所以前序的第一个元素就是二叉树的根,再到中序里面找到这个值;这个值左边的的数就是左子树的,右边的数就是右子树的。
不断重复这个步骤,就可以确定二叉树的节点位置。
然后我们可以利用bfs进行层序输出,注意:一定要是节点才能入队列,还要记录输出节点的个数
这里还有一篇后序中序确定二叉树的,里面也有更详细得解释!
https://blog.csdn.net/weixin_43535668/article/details/104401941
具体看代码解释~~
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn = 50;
int mid[maxn];//中序
int fr[maxn];//前序
int n;//节点数量
struct node
{
int l, r;//左右节点的值
};
node a[maxn];
int build(int la, int ra, int lb, int rb)la,ra表示中序遍历 lb,rb表示前序遍历
{
if (la > ra)
return 0;//如果输入不合理的话
int rt = fr[lb];
int i = 0;
while (mid[i] != rt)
{
i++;
}
a[rt].l = build(la, i - 1, lb + 1, lb + i - la);//前序遍历第一个是跟,后面先后跟着一团左子树和一团右子树
a[rt].r = build(i + 1, ra, lb + i - la + 1, rb);
return rt;
}
void dfs(int root)//深度优先递归
{
if (a[root].l == 0 && a[root].r == 0)//出口,已经是树叶节点的情况
return;
else
{
swap(a[root].l, a[root].r);//交换两者的值,在<algorithm>的头文件中带有
dfs(a[root].l);
dfs(a[root].r);
}
}
void bfs(int root)//广度优先遍历也就是层次遍历
{
queue<int> qu;
int count = 0;//计算要输出的节点数量
qu.push(root);
while (!qu.empty())
{
int t;
t = qu.front();
qu.pop();
count++;
cout << t;
if (count != n)
{
cout << " ";
}
if (a[t].l != 0)//判断是否是节点再进队列
{
qu.push(a[t].l);
}
if (a[t].r != 0)
{
qu.push(a[t].r);
}
}
}
int main()
{
int i, j;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> mid[i];
}
for (int i = 0; i < n; i++)
{
cin >> fr[i];
}
int root=build(0, n - 1, 0, n - 1);
dfs(root);
bfs(root);
system("pause");
return 0;
}