package datastructure;
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.servlet.*;
import javax.servlet.http.*;
class HTNode
{
int weight;
int parent;
int lchild;
int rchild;
}
public class HuffmanTree
{
private int pictureWidth=500;
private int pictureHeight=500;
public int s1,s2;
int n=(int)(2+9*Math.random());//随机生成结点的个数
int m=2*n-1;
public void draw(HttpServletResponse response)
{
response.reset();
response.setContentType( "image/png ");
BufferedImage image=new BufferedImage(pictureWidth,pictureHeight,BufferedImage.TYPE_INT_RGB);
Graphics2D g2d=image.createGraphics();
g2d.setPaint(Color.WHITE);
g2d.fillRect(0,0,pictureWidth, pictureHeight);
g2d.setPaint(Color.RED);
g2d.setFont(new Font( "TimesRoman ",Font.BOLD,24));
g2d.drawString( "赫夫曼树和赫夫曼编码演示 ",100,20);
HTNode HT[]=new HTNode[m+1];
HTNode HC[]=new HTNode[n];
HuffmanCoding(HT,HC,g2d);
g2d.dispose();
ServletOutputStream sos=null;
try
{
sos=response.getOutputStream();
ImageIO.write(image, "PNG ",sos);
sos.close();
}
catch (IOException ex){
}
}
public void HuffmanCoding(HTNode HT[],HTNode HC[],Graphics2D g2d)
{
int i;
int w[]=new int[n];//存取每个结点的权值
for(i=0;i <n;i++)
w[i]=(int)(1+20*Math.random());
for(i=1;i <=n;i++)
{
HT[i].weight=w[i-1];
HT[i].parent=0;
HT[i].lchild=0;
HT[i].rchild=0;
}
for(i=n+1;i <=m;i++)
{
HT[i].weight=0;
HT[i].parent=0;
HT[i].lchild=0;
HT[i].rchild=0;
}
for(i=n+1;i <=m;i++)
{
Select(HT,i-1);
HT[s1].parent=i;
HT[s2].parent=i;
HT[i].lchild=s1;
HT[i].rchild=s2;
HT[i].weight=HT[s1].weight+ HT[s2].weight;
}
for(i=1;i <=n;i++)
g2d.drawString(Integer.toString(HT[i].weight),20*i,100);
}
public void Select(HTNode HT[],int n)