题目如下:
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
题意就是给出了二叉树的中序遍历序列和后序遍历序列,要求输出层次遍历序列。因为正好数据结构看了这块的相关内容,于是就按照书上的方式实现了一下。首先用递归的方式来处理中序遍历序列和后序遍历序列从而建立对应的二叉树。具体思想就是后序遍历序列的最后一个元素为根结点,在中序遍历序列中找到根结点所在位置,该位置前面的在根结点的左子树上,后面的在根结点的右子树上,然后分别按同样的方式递归建立左右子树即可,传参时中序遍历序列根结点前面的部分也对应后序遍历相应前面的部分,后面对应后面。建立完树之后对树进行层次遍历,这个也很经典,借助队列的辅助就可以完成。代码如下:
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
typedef struct BiNode{
int data;
struct BiNode *lChild, *rChild;
}BiNode,*BiTree;
//根据中序和后序遍历的序列通过递归建立树
BiTree buildTree(vector<int> inOrder, int front1, int rear1, vector<int> postOrder,int front2, int rear2)
{
int half = -1;
int length;
if (front1 > rear1 || front2 > rear2)
return nullptr;
for (int i = front1;i <= rear1;i++)
{
if (inOrder[i] == postOrder[rear2])
{
half = i;
break;
}
}
if (half == -1)
return nullptr;
length = half - front1;
BiTree T = (BiTree)malloc(sizeof(BiNode));
T->data = inOrder[half];
T->lChild = buildTree(inOrder, front1, half - 1, postOrder,front2 ,front2 + length - 1);
T->rChild = buildTree(inOrder, half + 1, rear1, postOrder, front2 + length, rear2 - 1);
return T;
}
//将树进行层次遍历
void levelTraversals(BiTree T)
{
int flag = 1;
BiTree p;
queue<BiTree> q;
if (T == nullptr)
return;
q.push(T);
while (!q.empty())
{
p = q.front();
q.pop();
if (flag == 1)
{
cout << p->data;
flag = 0;
}
else
cout << " " << p->data;
if(p->lChild)
q.push(p->lChild);
if (p->rChild)
q.push(p->rChild);
}
}
int main(void)
{
int n;
int num;
vector<int> postOrder;
vector<int> inOrder;
cin >> n;
for (int i = 0;i < n;i++)
{
cin >> num;
postOrder.push_back(num);
}
for (int i = 0;i < n;i++)
{
cin >> num;
inOrder.push_back(num);
}
BiTree T = buildTree(inOrder, 0, inOrder.size() - 1, postOrder, 0, postOrder.size() - 1);
levelTraversals(T);
return 0;
}
有一个问题是之前按照严蔚敏《数据结构》上的定义结构体的方式在VS2015上会报错,于是在typedef struct后加上了类名解决了该问题。然后代码完美通过了。