1020. Tree Traversals (25)
Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (<=30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:7 2 3 1 5 7 6 4 1 2 3 4 5 6 7Sample Output:
4 1 6 3 5 7 2
这道题说的很直白,没有什么绕绕弯弯的,就是树的建立(create),然后说是树的层序遍历(BFS)
容易写错的是create这部分,刚开始提交几次一直显示段错误,后来检查才发现:
for(int k=inL;k<=intR;i++) ,我习惯性的写成从i=0到i<=n了。。。
第二处错误就是root->lchild=create(posL,posL+numLeft-1,inL,k-1); root->rchild=create(posL+numLeft,posR,k+1,inR);
这两句话,要么是递归的下标写错,要么就是忘记赋值了,只想到递归。。。。
在BFS里面要注意的就是,必须判断它的左(右)子树是否是NULL,非空才能加入队列~
#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 50;
int ino[maxn], pos[maxn];
int n;
struct Node {
int data;
Node* lchild;
Node* rchild;
};
Node* create(int posL, int posR, int inL, int inR) {
if (posL > posR) {
return NULL;
}
Node* root = new Node;
root->data = pos[posR];
int k;
for (k = inL; k <=inR ; k++) {
if (pos[posR] == ino[k]) {
break;
}
}
int numLeft = k - inL;
root->lchild=create(posL, posL + numLeft - 1, inL, k - 1);
root->rchild=create(posL + numLeft, posR - 1, k + 1, inR);
return root;
}
void BFS(Node* root) {
queue<Node*> q;
q.push(root);
int tt = 0;
while (!q.empty()) {
Node* top = q.front();
q.pop();
printf("%d", top->data);
tt++;
if (tt == n) {
printf("\n");
}
else {
printf(" ");
}
if (top->lchild!=NULL) { q.push(top->lchild); }
if (top->rchild!=NULL) { q.push(top->rchild); }
}
}
int main() {
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &pos[i]);
}
for (int i = 0; i < n; i++) {
scanf("%d", &ino[i]);
}
Node* root = create(0, n - 1, 0, n - 1);
BFS(root);
return 0;
}