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 7
Sample Output:
4 1 6 3 5 7 2
这题思路很简单,没有那没多花里胡哨的东西,但是如果没有接触过的话短时间可能很难写出来。首先就是根据中序和后序序列递归构建二叉树,再对这个二叉树进行层次遍历,实际上就是对这个二叉树进行广度优先遍历,这个地方需要借助队列来实现。
代码如下:
#include <iostream>
#include<vector>
#include<queue>
using namespace std;
struct Node
{
int key;
Node *leftNode;
Node *rightNode;
};
Node * createTree(vector<int> postOrder, vector<int> inOrder) //根据后根序列和中根序列创建二叉树
{
if (postOrder.size() == 0)
{
return NULL;
}
int key = postOrder[postOrder.size() - 1];
int index = -1;
for (int i = 0; i < inOrder.size(); i++)
{
if (inOrder[i] == key)
{
index = i;
break;
}
}
vector<int> leftPost, leftIn, rightPost, rightIn;
for (int i = 0; i < index; i++)
{
leftPost.push_back(postOrder[i]);
leftIn.push_back(inOrder[i]);
}
for (int i = index; i < inOrder.size()-1; i++)
{
rightIn.push_back(inOrder[i+1]);
rightPost.push_back(postOrder[i]);
}
Node *root=new Node;
root->key = key;
root->leftNode = NULL;
root->rightNode = NULL;
root->leftNode = createTree(leftPost, leftIn);
root->rightNode = createTree(rightPost, rightIn);
return root;
}
void BFS(Node *root) //BFS对树进行广度优先遍历
{
queue<Node> que;
que.push(*root);
while (que.empty() != 1)
{
Node node=que.front();
if (que.size() == 1 && node.leftNode == NULL && node.rightNode == NULL)
{
cout << node.key;
}
else
{
cout << node.key << " ";
}
que.pop();
if(node.leftNode!=NULL)
{
que.push(*node.leftNode);
}
if (node.rightNode != NULL)
{
que.push(*node.rightNode);
}
}
}
int main()
{
int N;
cin >> N;
vector<int> postOrder(N), inOrder(N);
for (int i = 0; i < N; i++)
{
cin >> postOrder[i];
}
for (int i = 0; i < N; i++)
{
cin >> inOrder[i];
}
Node *root = createTree(postOrder, inOrder); //创建二叉树
BFS(root); //对树广度优先遍历
system("pause");
return 0;
}