找回密码
 立即注册→加入我们

QQ登录

只需一步,快速开始

搜索
热搜: 下载 VB C 实现 编写
查看: 2059|回复: 0

由先序遍历和中序遍历回复树结构

[复制链接]

307

主题

228

回帖

7349

积分

用户组: 真·技术宅

UID
2
精华
76
威望
291 点
宅币
5599 个
贡献
253 次
宅之契约
0 份
在线时间
949 小时
注册时间
2014-1-25
发表于 2014-9-1 17:44:38 | 显示全部楼层 |阅读模式

欢迎访问技术宅的结界,请注册或者登录吧。

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

×
动态规划法,找到左子树和右子树解即为整个树的解
  1. #include <iostream>
  2. using namespace std;

  3. #define min(x,y) ((x<y)?x:y)
  4. #define arr(x,y) arr[(x)*size2+(y)]

  5. struct NODE
  6. {
  7.         NODE* pLeft;
  8.         NODE* pRight;
  9.         char chValue;
  10. };

  11. NODE* tranverse(char* pre,int preb,int pree,char* in,int inb,int ine)
  12. {
  13.         NODE* father=new NODE();
  14.         father->chValue=pre[preb];
  15.         int i=inb;
  16.         for(;i<=ine;i++)
  17.         {
  18.                 if(in[i] == pre[preb])
  19.                         break;
  20.         }
  21.         father->pLeft=NULL;
  22.         father->pRight=NULL;

  23.         int l1=i-inb,l2=ine-i;//pre[preb+1,preb+l1]=>in[inb,inb+l1-1]  pre[preb-l2+1,pree]=>in[ine-l2+1,ine]
  24.         if(l1>0)
  25.         {
  26.                 father->pLeft=tranverse(pre,preb+1,preb+l1,in,inb,inb+l1-1);
  27.         }
  28.         if(l2>0)
  29.         {
  30.                 father->pRight=tranverse(pre,pree-l2+1,pree,in,ine-l2+1,ine);
  31.         }
  32.         return father;
  33. }

  34. void Rebuild(char* pPreOrder,char* InOrder,int nTreeLen,NODE** pRoot)
  35. {
  36.         *pRoot=tranverse(pPreOrder,0,nTreeLen-1,InOrder,0,nTreeLen-1);
  37. }

  38. void main()
  39. {
  40.         NODE* root;
  41.         Rebuild("abdcef","dbaecf",6,&root);
  42.         cout<<root->chValue<<endl;
  43. }
复制代码
回复

使用道具 举报

QQ|Archiver|小黑屋|技术宅的结界 ( 滇ICP备16008837号 )|网站地图

GMT+8, 2024-5-5 12:29 , Processed in 0.031603 second(s), 27 queries , Gzip On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

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