理论知识参见 《 数据结构基础》第二版 张力译 第382页--387页;
好了不多说啦。我的代码如下供大家批评。希望指出改进意见。
#include "BST.h"
#include <iostream>
using namespace std;
int BST::KnuthMin(int i,int j)
{
int k=i+1;
int ck=c[i][k-1]+c[k][j];
for (int l=i+2;l<=j;l++)
{
if (ck>c[i][l-1]+c[l][j])
{
ck=c[i][l-1]+c[l][j];
k=l;
}
}
return k;
}
void BST::Obst(int *p,int *q,int n)
{
for (int i=0;i<n;i++)
{
w[i][i]=q[i];
r[i][i]=c[i][i]=0;
w[i][i+1]=q[i]+q[i+1]+p[i+1];
r[i][i+1]=i+1;
c[i][i+1]=w[i][i+1];
}
w[n][n]=q[n];
r[n][n]=c[n][n]=0;
for (int m=2;m<=n;m++)
for (i=0;i<=n-m;i++)
{
int j=i+m;
w[i][j]=w[i][j-1]+p[j]+q[j];
int k=KnuthMin(i,j);
c[i][j]=w[i][j]+c[i][k-1]+c[k][j];
r[i][j]=k;
}
}
void BST::Construct(int *a,int len)
{
root=Construct(a,0,len);
}
BSTNode* BST::Construct(int *a,int i,int j)
{
if (i==j)
return NULL;
BSTNode * bn=new BSTNode(a[r[i][j]]);
bn->leftchild=Construct(a,i,r[i][j]-1);
bn->rightchild=Construct(a,r[i][j],j);
return bn;
}
#ifndef _BST_
#define _BST_
#include <iostream>
using namespace std;
class BSTNode
{
friend class BST;
public:
BSTNode(int e=0)
{
data=e;
leftchild=rightchild=0;
}
private:
BSTNode*leftchild,*rightchild;
int data;
};
class BST
{
public:
BST(int initlen=100,BSTNode* BN=0)
{
root=BN;
arraylen=initlen+1;
r=new int *[arraylen];
c=new int *[arraylen];
w=new int *[arraylen];
for (int i=0;i<arraylen;i++)
{
r[i]=new int[arraylen];
c[i]=new int[arraylen];
w[i]=new int[arraylen];
fill(r[i],r[i]+arraylen,0);
fill(c[i],c[i]+arraylen,0);
fill(w[i],w[i]+arraylen,0);
}
}
void Obst(int *p,int *q,int n);
void Construct(int *a,int len);
private:
BSTNode * Construct(int *a,int i,int j);
int KnuthMin(int i,int j);
int arraylen;
int **r;
int **c;
int **w;
BSTNode *root;
};
#endif
#include <iostream>
#include "BST.h"
using namespace std;
void main()
{
BST b(4);
int p[5]={0,3,3,1,1};//p[0] 未用
int q[5]={2,3,1,1,1};
b.Obst(p,q,4);
int a[5]={0,10,15,20,25};//a[0]未用
b.Construct(a,4);
}

本文分享了一个基于《数据结构基础》中介绍的最优二叉搜索树算法的C++实现。该实现通过动态规划确定了构造最优二叉搜索树所需的中间节点,并提供了构造树的方法。此外,还展示了如何使用这个类来初始化一个实例并构建最优二叉搜索树。
3284

被折叠的 条评论
为什么被折叠?



