- UID
- 2
- 精华
- 积分
- 7736
- 威望
- 点
- 宅币
- 个
- 贡献
- 次
- 宅之契约
- 份
- 最后登录
- 1970-1-1
- 在线时间
- 小时
|
动态规划法,找到左子树和右子树解即为整个树的解
- #include <iostream>
- using namespace std;
- #define min(x,y) ((x<y)?x:y)
- #define arr(x,y) arr[(x)*size2+(y)]
- struct NODE
- {
- NODE* pLeft;
- NODE* pRight;
- char chValue;
- };
- NODE* tranverse(char* pre,int preb,int pree,char* in,int inb,int ine)
- {
- NODE* father=new NODE();
- father->chValue=pre[preb];
- int i=inb;
- for(;i<=ine;i++)
- {
- if(in[i] == pre[preb])
- break;
- }
- father->pLeft=NULL;
- father->pRight=NULL;
- 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]
- if(l1>0)
- {
- father->pLeft=tranverse(pre,preb+1,preb+l1,in,inb,inb+l1-1);
- }
- if(l2>0)
- {
- father->pRight=tranverse(pre,pree-l2+1,pree,in,ine-l2+1,ine);
- }
- return father;
- }
- void Rebuild(char* pPreOrder,char* InOrder,int nTreeLen,NODE** pRoot)
- {
- *pRoot=tranverse(pPreOrder,0,nTreeLen-1,InOrder,0,nTreeLen-1);
- }
- void main()
- {
- NODE* root;
- Rebuild("abdcef","dbaecf",6,&root);
- cout<<root->chValue<<endl;
- }
复制代码 |
|