最优查找二叉树


        理论知识参见 《 数据结构基础》第二版 张力译  第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);
}


 

    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值