1二叉树的递归遍历:
给定中序和后序序列,建立先序序列
#include<bits/stdc++.h>
using namespace std;
/*
8
7 8 11 3 5 16 12 18
8 3 11 7 16 18 12 5
3
*/
int lchild[10000]={0};
int rchild[10000]={0};
int mid[10000]={0};
int aft[10000]={0};
int build(int l1,int r1,int l2,int r2){
if(l1>r1)return 0;
int root=aft[r2];
int cnt=0;
while(mid[cnt]!=root)cnt++;
int ans=cnt-l1;
lchild[root]=build(l1,cnt-1,l2,l2+ans-1);
rchild[root]=build(cnt+1,r1,l2+ans,r2-1);
return root;
}
int best_sum=1000000;
int best=1000000;
void dfs(int sum,int v){
sum+=v;
if(!lchild[v]&&!rchild[v]){
if(sum<best_sum||(sum==best_sum&&v<best)){
best=v;
best_sum=sum;
}
}
if(lchild[v])dfs(sum,lchild[v]);
if(rchild[v])dfs(sum,rchild[v]);
}
int main(){
int n;
cin>>n;
for(int i=0;i<n;i++)cin>>mid[i];
for(int i=0;i<n;i++)cin>>aft[i];
int root=build(0,n-1,0,n-1);
dfs(0,root);
cout<<best_sum;
}
2给出如下数据,构建二叉树:
(11,LL) (7,LLL) (8,R) (5,) (4,L) (13,RL) (2,LLR) (1,RRR) (4,RR) ()
#include<bits/stdc++.h>
using namespace std;
//(11,LL) (7,LLL) (8,R) (5,) (4,L) (13,RL) (2,LLR) (1,RRR) (4,RR) ()
struct node{
int v;
node * left;
node * right;
node():left(NULL),right(NULL),v(0){}
};
node * root;
bool flag=true;
void addnode(char *s,int v){
node * temp=root;
for(int i=0;i<strlen(s);i++){
if(s[i]=='L'){
if(temp->left==NULL){
node * l=new node;
temp->left=l;
temp=l;
}
}else if(s[i]=='R'){
node * l=new node;
temp->right=l;
temp=l;
}
}
if(temp->v>0)flag=false;
temp->v=v;
}
bool read(){
char s[50];
root=new node;
while(true){
memset(s,'\0',sizeof(s));
scanf("%s",s);
if(strcmp(s,"()")==0)break;
int v;
sscanf(&s[1],"%d",&v);
addnode(strchr(s,',')+1,v);
}
return true;
}
void dfs(node * r){
if(r==NULL)return ;
else{
cout<<r->v<<" ";
if(r->left)dfs(r->left);
if(r->right)dfs(r->right);
}
}
int main(){
read();
dfs(root);
}
3天平问题
```cpp
#incldue<bits/stdc++.h>
using namespace std;
bool solve(int &w){
int l1,l2,r1,r2;
cin>>l1>>r1>>l2>>r2;
bool s1=true;
bool s2=true;
if(!11)s1=solve(l1);
if(!l2)s2=solve(l2);
w=l1+l2;
return (s1&&s2&&l1*r1==l2*r2);
}
int main(){
cout<<solve(0);
}