题目描述
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 7
Sample Output:
4 1 6 3 5 7 2
也就是说给定一棵二叉树的后序序列和中序序列,构建这颗树并输出其层序序列。
题解
我们知道根据一棵二叉树的前序或后序序列,可以找到这颗树的根结点;而若知道二叉树的根节点及其中序序列,则可推出这颗树的左右子树。
所以用递归的方法,利用后序序列找到根结点,再利用中序序列划分左右子树,并分别对左右子树重复上面步骤。递归结束的条件是左(右)子树为空。代码采用了另一种判断递归结束的写法,本质上相同。
#include<iostream>
#include<vector>
#include<stdio.h>
#include<stdlib.h>
#include<map>
#include<algorithm>
#include<string>
#include<list>
#include<cmath>
#include<queue>
using namespace std;
struct treeNode {
struct treeNode *left;
struct treeNode *right;
int data;
};
typedef enum {
LEFT,
RIGHT
}child;
typedef struct treeNode* tree;
void createTree(int data, tree T, child flag);
tree rebuildTree(int in[], int post[], int n);
void reTree(int in[], int post[], int inA, int inB, int postA, int postB, tree T);
void levelSearch(tree T, int n);
int inOrder[31];
int postOrder[31];
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> postOrder[i];
}
for (int i = 1; i <= n; ++i) {
cin >> inOrder[i];
}
tree BiT = rebuildTree(inOrder, postOrder, n);
levelSearch(BiT, n);
return 0;
}
void createTree(int data, tree T, child flag) {
treeNode *newNode = (treeNode*)malloc(sizeof(treeNode));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
if (flag == LEFT) T->left = newNode;
else T->right = newNode;
}
tree rebuildTree(int in[], int post[], int n) {
tree root = (treeNode*)malloc(sizeof(treeNode));
root->data = post[n];
root->left = NULL;
root->right = NULL;
reTree(in, post, 1, n, 1, n, root);
return root;
}
void reTree(int in[], int post[], int inA, int inB, int postA, int postB, tree T) {
int i;
for (i = inA; i <= inB; i++) {
if (in[i] == post[postB]) break;
}
if (inA != i) {
createTree(post[postA + i - inA - 1], T, LEFT);
reTree(in, post, inA, i - 1, postA, postA + i - inA - 1, T->left);
}
if (inB != i) {
createTree(post[postB - 1], T, RIGHT);
reTree(in, post, i + 1, inB, postA + i - inA, postB - 1, T->right);
}
}
void levelSearch(tree T, int n) {
queue<treeNode*> Q;
treeNode* node;
Q.push(T);
while (!Q.empty()) {
node = Q.front();
Q.pop();
cout << node->data;
if (node->left) Q.push(node->left);
if (node->right) Q.push(node->right);
if (--n != 0) cout << " ";
}
}