1020 Tree Traversals (25分)
题目链接:PAT A 1020
题目大意:给出一棵树的后序遍历和中序遍历,要求求出该树的层序遍历。
思路分析:根据后序遍历和中序遍历可以构建出唯一的一颗二叉树,用到了递归的求解方法。对于每一棵树,后序遍历的最后一个元素就是该树的根节点,然后在中序遍历中找到这个元素,记录对应的下标,左面的元素就是这棵树的左子树,右面的树就是这棵树的右子树,然后递归求解,重复上述过程,就可以构建出唯一的一颗二叉树,最后直接进行层序遍历即可~
ps:如果你对递归感觉很懵,理解的不透彻,可以先把参考代码拷贝到编译器中,然后用调试的方法跟踪执行,看看具体是怎样的执行的,用笔在纸上将完整的过程推导一遍,反复理解。递归的理解需要一个过程,坚持下来肯定会有收获的!
AC代码:
#include<iostream>
#include<queue>
using namespace std;
struct node{
int data;
node* lchild;
node* rchild;
};
int n, postorder[35], inorder[35]; //后序遍历和中序遍历数组
node* create(int postl, int postr, int inl, int inr) {
if(postl > postr) //递归返回条件
return NULL;
node* root = new node;
root->data = postorder[postr];
int k;
for(k = inl; k <= inr; k++) { //在中序遍历中查找根节点的索引
if(inorder[k] == postorder[postr])
break;
}
int numleft = k - inl; //左子树的数目
root->lchild = create(postl, postl + numleft - 1, inl, k - 1); //递归建树
root->rchild = create(postl + numleft, postr - 1, k + 1, inr);
return root;
}
void layerorder(node* root) { //层序遍历
queue<node*> q;
q.push(root);
int cnt = 0; //记录输出空格用
while(q.empty() != true) {
node* now = q.front();
q.pop();
cout << now->data;
cnt++;
if(cnt != n)
cout << " ";
if(now->lchild != NULL)
q.push(now->lchild);
if(now->rchild != NULL)
q.push(now->rchild);
}
}
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* root = create(0, n - 1, 0, n - 1);
layerorder(root);
return 0;
}