思路:
這是一道關於二叉樹確定以及遍歷的題目。首先我們要了解前序中序的特點。
前序:根節點->左節點->右節點
中序:左節點->根結點->右節點
所以前序的第一個元素就是二叉樹的根,再到中序裏面找到這個值;這個值左邊的的數就是左子樹的,右邊的數就是右子樹的。
不斷重複這個步驟,就可以確定二叉樹的節點位置。
然後我們可以利用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;
}