Binary Tree Traversals
题目链接:HDU - 1710
测试样例:
Sample Input 9 1 2 4 7 3 5 8 9 6 4 7 2 1 8 5 9 3 6 Sample Output 7 4 2 8 9 5 6 3 1
已知前序中序求后序
#include<stdio.h>
#include<algorithm>
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<cmath>
using namespace std;
typedef long long ll;
const int N=1010;
int pre[N],in[N],post[N],id[N],p;
//前序起点、前序终点、中序起点、中序终点
void dfs(int l,int r,int L,int R)
{
int root=id[pre[l]];
int ls=root-L;//中序左子树节点个数
int rs=R-root;//中序右子树节点个数
if(ls)//左子树非空
dfs(l+1,l+root,L,root-1); //dfs(l+1,l+root-1,L,root-1); 也能过
if(rs)//右子树非空
dfs(l+ls+1,r,root+1,R);
post[++p]=pre[l];//当左子树是空的右子树也是空的说明是叶节点、记录即可
}
int main()
{
int n;
while(cin>>n)
{
p=0;
for(int i=1;i<=n;i++)
cin>>pre[i];
for(int i=1;i<=n;i++)
{
cin>>in[i];
id[in[i]]=i;
}
dfs(1,n,1,n);
for(int i=1;i<n;i++)
cout<<post[i]<<" ";
cout<<post[n]<<endl;
}
return 0;
}
[NOIP2001]求先序排列
题目链接:计蒜客 - T2113
测试样例:
扫描二维码关注公众号,回复:
9196479 查看本文章
样例输入
BADC
BDCA
样例输出
ABCD
已知中序后序求先序
1 #include<string.h> 2 #include<iostream> 3 #include<stdio.h> 4 #include<algorithm> 5 #include<queue> 6 #include<map> 7 #include<cmath> 8 using namespace std; 9 #define inf 0x3f3f3f3f 10 const int N=500200*2; 11 12 char s1[10],s2[10]; 13 void w(int l1,int r1,int l2,int r2) 14 { 15 int k=-1; 16 for(int i=l1; i<r1; i++) 17 { 18 if(s1[i]==s2[r2-1]) 19 { 20 printf("%c",s1[i]); 21 k=i; 22 break; 23 } 24 } 25 if(k>l1) //左 26 w(l1,k,l2,k-l1+l2); 27 if(r1>k+1) //右 28 w(k+1,r1,k-l1+l2,r2-1); 29 } 30 31 int main() 32 { 33 cin>>s1>>s2; 34 int l1=strlen(s1); 35 int l2=strlen(s2); 36 w(0,l1,0,l2); 37 return 0; 38 }
二叉搜索树
题目链接: HDU - 3791
题意:判断两个序列是否能够构成二叉搜索树
#include<stdio.h> #include<algorithm> #include<iostream> #include<string.h> using namespace std; typedef long long ll; char a[15],b[15]; bool flag; struct node { int x;// 值 node *l,*r; }; node *insertt(node *p,int xx)//依次插入每个值 { if(p==NULL)//如果当前节点为空则插入 { node *q=new node;//申请一个动态空间 q->x=xx;//赋值 q->l = q->r =NULL;//左右儿子为空 return q;//返回此节点的地址 } //说明有值,继续往下找,遵循左小右大 if(p->x>xx)//xx<左儿子,继续往左走 p->l=insertt(p->l,xx); else p->r=insertt(p->r,xx); return p; } void check(node *root,node *tree)//传入地址 { if(root!=NULL&&tree!=NULL)//说明此节点两棵树都有值,只需判断值是否相等 { check(root->l,tree->l);//中序遍历 if(root->x!=tree->x)//判断此节点的值是否和标准树相等 flag=0; check(root->r,tree->r); } else if(root!=NULL||tree!=NULL)//只有一个节点有值 flag=0; } int main() { int n; while(~scanf("%d",&n)&&n) { node *root=NULL;//标准树地址为空 scanf("%s",a); int la=strlen(a); for(int i=0; i<la; i++) root=insertt(root,a[i]-'0');//构建一颗标准树 for(int i=1; i<=n; i++) { flag=1; node *tree=NULL;//判断树地址为空 scanf("%s",b); int lb=strlen(b); for(int i=0; i<lb; i++) tree=insertt(tree,b[i]-'0'); check(root,tree); if(flag) printf("YES\n"); else printf("NO\n"); } } return 0; }