給定一棵二叉樹的後序遍歷和中序遍歷,請你輸出其層序遍歷的序列。這裏假設鍵值都是互不相等的正整數。
輸入格式:
輸入第一行給出一個正整數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
#include <iostream>
#include <queue>
using namespace std;
struct Node {
int data;
Node* lc, * rc;
};
Node* buildTree(int* post, int* in, int n) {
if (n == 0)
return NULL;
int* mid = in;
while (*(post + n - 1) != *mid)mid++;
Node* T = new Node;
T->data = *mid;
int m = mid - in;
T->lc = buildTree(post, in, m);
T->rc = buildTree(post + m, mid + 1, n - 1 - m);
return T;
}
int main() {
queue<Node*>q;
int N, post[30], in[30], vis[30];
cin >> N;
for (int i = 0; i < N; ++i)
cin >> post[i];
for (int i = 0; i < N; ++i)
cin >> in[i];
q.push(buildTree(post, in, N));
int i = 0;
while (!q.empty()) {
cout << (i++ ? " " : "") << q.front()->data;
if (q.front()->lc)q.push(q.front()->lc);
if (q.front()->rc)q.push(q.front()->rc);
q.pop();
}
return 0;
}