文章

6

粉丝

0

获赞

35

访问

4.5k

头像
二叉树(北京邮电大学) 题解:
P1561 北京邮电大学机试题
发布于 2026年3月
阅读数 754

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. void f(string a,string b){
  4. if(a.size()==0)return;//a为0返回
  5. char c=a[0];//前序的第一个元素是根记录下来;
  6. int p=b.find(c);//在中序找到根的位置
  7. string lb=b.substr(0,p);//将中序的左子树记录下来
  8. string rb=b.substr(p+1,b.size()-(p+1));//将中序的右子树记录下来
  9. string la=a.substr(1,lb.size());//将前序的右左子树记录下来
  10. string ra=a.substr(1+lb.size(),a.size()-(1+lb.size()));//将前序的右子树记录下来
  11. f(la,lb);//先递归左
  12. f(ra,rb);//后递归右
  13. cout<<c;//返回根
  14. }//左右根
  15. int main(){
  16. string a,b;
  17. cin>>a>>b;
  18. f(a,b);
  19. }
登录查看完整内容


登录后发布评论

暂无评论,来抢沙发