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
心得
需要掌握通过两个遍历构建二叉树。然后通过BFS输出二叉树。如何通过后序遍历和中序遍历构成二叉树。步骤如下:
- 后序遍历,最后一个节点一定是根节点。去中序遍历里面寻找这个根节点,然后得到左右的数量
- 后续遍历的顺序是 左,右,子。中序遍历是左,子,右。对于同一个子来说,左右的数量应该是相同的。
- 通过1得到的数量,回到后序遍历里面,通过数量,分成两个子树,递归遍历。同样的中序遍历里面也要通过数量分开一下。
- Node* creatTree(int postL, int postR, int inL, int inR) 如此构建函数即可。
root->left = creatTree(postL, postL+number-1, inL, i-1);
root->right = creatTree(postL + number, postR-1, i+1, inR);
如上进行递归
C++构造结构体可直接struct node{};不typedef也行。
在进行BFS层次搜索树的时候,可以使用队列,每一层往队列里面存,一直到队列为空。
网上也有不构建子树的,我还是觉得构建子树才是王道!
#include <iostream>
#include <queue>
using namespace std;
int N;
int postOrder[30];
int inOrder[30];
struct Node {
int val;
Node *left;
Node *right;
};
Node* creatTree(int postL, int postR, int inL, int inR) {
if (postL > postR)return NULL;
Node *root = new Node;
root->val = postOrder[postR];
int i;
for (i = inL; i < inR; i++)
{
if (inOrder[i] == postOrder[postR])break;
}
int number = i - inL;
root->left = creatTree(postL, postL+number-1, inL, i-1);
root->right = creatTree(postL + number, postR-1, i+1, inR);
return root;
}
void BFS(Node *root) {
queue<Node*> qu;
qu.push(root);
while (!qu.empty())
{
Node*node = qu.front();
cout << node->val;
qu.pop();
if (node->left != NULL) {
qu.push(node->left);
}
if (node->right != NULL) {
qu.push(node->right);
}
if (!qu.empty())cout << " ";
}
}
int main() {
cin >> N;
for (int i = 0; i < N; i++)
{
cin >> postOrder[i];
}
for (int i = 0; i < N; i++)
{
cin >> inOrder[i];
}
Node * node =creatTree(0, N - 1, 0, N - 1);
BFS(node);
return 0;
}
附加一个先序遍历,cout的不同位置对应着不同的遍历方式。
void pre(Node*node) {
cout << node->val;
if(node->left!=NULL)pre(node->left);
if (node->right != NULL)pre(node->right);
}