Java实现哈夫曼树

最近有点忙,姑且先放上有注释的代码,有时间再来补充一些技术细节吧

/**
 * 
 */
/**
 * @author 32809
 *
 */
package haff;

public class node {
	node left;
	node right;
	int num;
	char key;//新建链表
	public void node() {
		left = null;
		right = null;
		key = ' ';//创建节点
	}

	private void printCode(node node, String string) {
		if (node.left != null) {
			printCode(node.left, string + 0);
		}
		if (node.right != null) {
			printCode(node.right, string + 1);//左节点+0,右节点+1,不得不说java在这方面比c++好用多了
		}
		if (node.left == null && node.right == null 
				//&& node.key != ' '
				) {
			System.out.println(node.key + "\t" + string + "\t" + node.num);
		}
	}

	public static void main(String[] argv) {
		String b = "aaaabcc";//测试字符串
		node count2[] = new node[256];
		int t = 0;
		for (int i = 0; i < 256; i++) {
			count2[i] = new node();
		}//为二百五十六种as码的的字符设置空间
		for (int i = 0; i < b.length(); i++) {
			for (int j = 0; j <= 256; j++) {
				if (j == 256) {
					count2[t].key = b.charAt(i);
					count2[t].num = 1;
					t++;//之前没有该字符则创建该字符
				} else {
//			System.out.println(b.charAt(i));
					if (count2[j].key == b.charAt(i)) {
						count2[j].num++;
						break;
					}//已有该字符则计数
				}
			}
		}
        node count[]=new node[t];
        for(int i=0;i<t;i++)count[i]=count2[i];
		for (int i = 0; i < count.length-1; i++) {
			for (int j = 0; j < count.length-i; j++) {
				for (int k = j; k < count.length - i - 1; k++) {
					if (count[k].num < count[k + 1].num) {
						node tran = new node();
						tran = count[k];
						count[k] = count[k + 1];
						count[k + 1] = tran;//冒泡排序
					}
				}
			}
			if(i<count.length-2)
			{
			node ne = new node();
			ne.left = count[count.length - i-1];
			ne.right = count[count.length-2 - i];
			ne.num = count[count.length - i - 2].num + count[count.length - i-1].num;
			ne.key = ' ';
			count[count.length - i - 2] = ne;
			}//实现哈夫曼树
			else
			{
				node ne = new node();
				ne.left=count[0];
				ne.right=count[1];
				count[0]=ne;
			}
		}
		node ne = count[0];
		ne.key=' ';
		String ans = " ";
		ne.printCode(ne, ans);//打印结果

	}

}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值