鱼C论坛

 找回密码
 立即注册
查看: 149|回复: 1

根据先序遍历跟中序遍历求后序遍历

[复制链接]
发表于 2024-2-26 20:56:53 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int main(){
  4.         string instr,poststr;
  5.         cin>>instr>>poststr;
  6.         function<void(string,string)>build=[&](string instr,string poststr)
  7.     {
  8. //在此补充代码
  9.         


  10.     };
  11.     build(instr,poststr);
  12.         return 0;
  13. }
  14. //  build(instr.substr(0,mid),poststr.substr(0,mid)); //在中序分为左右两个序列
  15. //  B B
  16. //  DC DCA
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2024-2-26 20:57:12 | 显示全部楼层
根据先序遍历和中序遍历求后续遍历的思路是:首先找出先序遍历的根节点,然后在中序遍历中找到根节点的位置,将中序遍历分为左子树和右子树。接着,再分别对左子树和右子树进行递归操作,直到遍历完所有节点。

下面是一种实现该功能的代码:
  1. #include <iostream>
  2. using namespace std;

  3. void build(string prestr, string instr) {
  4.     if (prestr.empty() || instr.empty()) {
  5.         return;
  6.     }

  7.     char root = prestr[0];  // 先序遍历的第一个字符为根节点
  8.     int pos = instr.find(root);  // 在中序遍历中找到根节点的位置

  9.     build(prestr.substr(1, pos), instr.substr(0, pos));  // 处理左子树
  10.     build(prestr.substr(pos + 1), instr.substr(pos + 1));  // 处理右子树

  11.     cout << root << " ";  // 输出后序遍历结果,即先处理左子树和右子树,最后输出根节点
  12. }

  13. int main() {
  14.     string prestr, instr;
  15.     cin >> prestr >> instr;
  16.     build(prestr, instr);
  17.    
  18.     return 0;
  19. }
复制代码


输入示例:
  1. ABCD DCBA
复制代码


输出示例:
  1. DCBA
复制代码


此代码中,我们首先通过递归的方式找到根节点,并分别递归处理左子树和右子树。最后,按照后序遍历的顺序输出结果。

需要注意的是,该代码假设输入的先序遍历和中序遍历都是合法的,并且没有重复的节点。如果输入不满足这些条件,那么需要对代码进行修改以处理错误情况。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-28 17:03

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表