/*链表结点定义*/
struct Tree
{
char data;
Tree * left,*right;
};
/*前序遍历*/
void preorder(Tree T){
if(T == null)
return;
printf("%c\n", T->data);
preorder(T->left);
preorder(T->right);
}
/*中序遍历*/
void inorder(Tree T){
if(T == null)
return;
inorder(T->left);
printf("%c\n", T->data);
inorder(T->right);
}
/*后序遍历*/
void postorder(Tree T){
if(T == null)
return;
postorder(T->left);
postorder(T->right);
printf("%c\n", T->data);
}
已知中序,后序转层序:
例题:1127 ZigZagging on a Tree
//left,right中序中子树的节点范围
//root后序中根节点
//depth在层序中节点的位置,相当于索引
后序的最后一个节点即为子树的根节点root,通过root找到中序根节点的位置i,所以左子树的范围就为left,i-1,而左子树的根节点为post[root-1-(right - i);
右子树相对容易一些,范围在i+1,right,根节点为root-1;
最后存储在map(可根据depth自动排序)里;
循环不变量:这里采用的左闭右闭区间
#include<iostream>
#include<vector>
#include<map>
using namespace std;
int n;
std::map<int, int> re;
std::vector<int> post(30);
std::vector<int> in(30);
void level(int left,int right,int root,int depth){
if(left > right) return ;
re[depth] = post[root];
int i = left;
while(i <= right&&in[i] != post[root]){ //找到中序遍历的根
i++;
}
level(left,i-1,root-1-(right - i),2*depth+1);//左子树
level(i+1,right,root-1,2*depth+2); //右子树
}
int main(int argc, char const *argv[])
{
cin>>n;
for (int i = 0; i < n; i++)
{
cin>>post[i];
}
for (int i = 0; i < n; ++i)
{
cin>>in[i];
}
level(0,n-1,n-1,0);
std::map<int, int>::iterator it = re.begin();
cout<<it->second;
while(++it != re.end())
cout<<' '<<it->second;
return 0;
}
已知中序,后序转前序:
#include<iostream>
#include<vector>
#include<map>
using namespace std;
int n;
std::vector<int> post(30);
std::vector<int> in(30);
void level(int left,int right,int root){
if(left > right) return ;
int i = left;
while(i <= right&&in[i] != post[root]){ //找到中序遍历的根
i++;
}
cout<<post[root]<<' '; //相当于根节点直接输出
level(left,i-1,root-1-(right - i));//左子树
level(i+1,right,root-1); //右子树
}
int main(int argc, char const *argv[])
{
cin>>n;
for (int i = 0; i < n; i++)
{
cin>>post[i];
}
for (int i = 0; i < n; ++i)
{
cin>>in[i];
}
level(0,n-1,n-1);
return 0;
}
已知前序,中序,转后序:
#include<iostream>
#include<vector>
#include<map>
using namespace std;
int n;
std::vector<int> pre(30);
std::vector<int> in(30);
void level(int left,int right,int root){
if(left > right) return ;
int i = left;
while(i <= right&&in[i] != pre[root]){ //找到中序遍历的根
i++;
}
level(left,i-1,root+1);//左子树
level(i+1,right,root+1+(i - left)); //右子树 注意右子树的根节点为root+1+左子树的部分i-left;
cout<<pre[root]<<' '; //最后输出根节点
}
int main(int argc, char const *argv[])
{
cin>>n;
for (int i = 0; i < n; i++)
{
cin>>pre[i];
}
for (int i = 0; i < n; ++i)
{
cin>>in[i];
}
level(0,n-1,0);
return 0;
}