1. 程式人生 > >L2-6 樹的遍歷(遞歸+bfs)

L2-6 樹的遍歷(遞歸+bfs)

scanf span can bsp style spa using void for

給定一棵二叉樹的後序遍歷和中序遍歷,請你輸出其層序遍歷的序列。這裏假設鍵值都是互不相等的正整數。

輸入格式:

輸入第一行給出一個正整數N(<=30),是二叉樹中結點的個數。第二行給出其後序遍歷序列。第三行給出其中序遍歷序列。數字間以空格分隔。

輸出格式:

在一行中輸出該樹的層序遍歷的序列。數字間以1個空格分隔,行首尾不得有多余空格。

輸入樣例:

7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

輸出樣例:

4 1 6 3 5 7 2

解題思路:用遞歸建立樹,然後用bfs遍歷即可。重點在於中序序列和後序序列之間子樹節點數的關系(15行)

#include<cstdio>
#include
<queue> using namespace std; typedef struct{ int lc, rc; }Tree; int a[40], b[40]; Tree tr[40]; int build(int al, int ar, int bl, int br) {//a為中序序列,b為後序序列 if(al > ar) return -1; //邊界條件 int root = b[br], p1 = al, p2; while(a[p1] != root) p1++; p2 = p1 - al; //確定後序中左子樹節點個數 tr[root].lc = build(al, p1 - 1
, bl, bl + p2 - 1); tr[root].rc = build(p1 + 1, ar, bl + p2, br - 1); return root; //返回根節點在後序中的位置 } int main(void) { int n; scanf("%d", &n); for(int i = 0; i < n; i++){ scanf("%d", &b[i]); } for(int i = 0; i < n; i++){ scanf("%d", &a[i]); } build(
0, n - 1, 0, n - 1); queue<int> q; int count = 0; q.push(b[n - 1]); while(!q.empty()){ int t = q.front(); q.pop(); if(tr[t].lc != -1) q.push(tr[t].lc); if(tr[t].rc != -1) q.push(tr[t].rc); printf("%d%c", t, ++count == n? \n : ); } return 0; }

L2-6 樹的遍歷(遞歸+bfs)