<题目重现>HDU - 1710
A binary tree is a finite set of vertices that is either empty or consists of a root r and two disjoint binary trees called the left and right subtrees. There are three most important ways in which the vertices of a binary tree can be systematically traversed or ordered. They are preorder, inorder and postorder. Let T be a binary tree with root r and subtrees T1,T2.
In a preorder traversal of the vertices of T, we visit the root r followed by visiting the vertices of T1 in preorder, then the vertices of T2 in preorder.
In an inorder traversal of the vertices of T, we visit the vertices of T1 in inorder, then the root r, followed by the vertices of T2 in inorder.
In a postorder traversal of the vertices of T, we visit the vertices of T1 in postorder, then the vertices of T2 in postorder and finally we visit r.
Now you are given the preorder sequence and inorder sequence of a certain binary tree. Try to find out its postorder sequence.
In a preorder traversal of the vertices of T, we visit the root r followed by visiting the vertices of T1 in preorder, then the vertices of T2 in preorder.
In an inorder traversal of the vertices of T, we visit the vertices of T1 in inorder, then the root r, followed by the vertices of T2 in inorder.
In a postorder traversal of the vertices of T, we visit the vertices of T1 in postorder, then the vertices of T2 in postorder and finally we visit r.
Now you are given the preorder sequence and inorder sequence of a certain binary tree. Try to find out its postorder sequence.
9 1 2 4 7 3 5 8 9 6 4 7 2 1 8 5 9 3 6
7 4 2 8 9 5 6 3 1<解决思路>
这是一道数据结构笔试考试的必考题目,但是使用程序如何实现?仿照递归遍历的方法进行构建,将后序遍历的顺序直接保存至数组中,这里用到distance,distance的返回值为查找值到起始索引的距离,有关distance的介绍见http://blog.youkuaiyun.com/lanzhihui_10086/article/details/41805503
这个题还有一个问题就是多组数据输入,每一组数据结束进入下一组时要清空原来的容器,当时因为这个WA好多次。
<AC代码>
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int pos,n;
vector<int>pre,in,post;
void rec(int l,int r){
if(l>=r)return ;
int root=pre[pos++];
int mid=distance(in.begin(),find(in.begin(),in.end(),root));
rec(l,mid);
rec(mid+1,r);
post.push_back(root);
}
void solve(){
pos=0;
rec(0,pre.size());
for(int i=0;i<post.size();i++){
if(i)cout<<" ";
cout<<post[i];
}
cout<<endl;
}
int main(){
while(cin>>n){
pre.clear();
in.clear();
post.clear();
for(int i=0;i<n;i++){
int k;cin>>k;
pre.push_back(k);
}
for(int i=0;i<n;i++){
int k;cin>>k;
in.push_back(k);
}
solve();
}
return 0;
}
本文探讨了如何从给定的二叉树前序和中序遍历序列构造出后序遍历序列,并通过递归算法实现了这一过程。文章提供了一个完整的C++代码示例,演示了如何使用STL容器和标准算法来解决问题。
1438

被折叠的 条评论
为什么被折叠?



