哈夫曼树 (优先队列建树) 及java实现

 

给每个节点的遍历打印了深度

 

import java.util.ArrayList;
import java.util.PriorityQueue;
/**
 * 优先队列建树
 * 泛型类
 * @author 叶叶叶
 *
 */
public class HuffmanTree {

	public static class TreeNode<E> implements Comparable<TreeNode>{
		E data;
		int weight;
		TreeNode left;
		TreeNode right;

		public TreeNode() {}
		public TreeNode(E data, int weight) {
			this(data,weight,null,null);
		}
		public TreeNode(E data, int weight,TreeNode left, TreeNode right) {
			this.data = data;
			this.weight = weight;
			this.left = left;
			this.right = right;
		}
		@Override
		public String toString() {
			return "TreeNode[data=" + data + ", weight=" + weight + "]";
		}
		@Override
		public int compareTo(TreeNode t) {
			return this.weight - t.weight;
		}
	}
	
	public static TreeNode creatTree(ArrayList<TreeNode> list) {
		PriorityQueue<TreeNode> pq = new PriorityQueue<>();
			for(TreeNode node:list)
				pq.add(node);		
		while(pq.size()>1) {
			TreeNode left = pq.poll();
			TreeNode right = pq.poll();
			TreeNode root = new TreeNode(null, left.weight + right.weight, left, right);
			pq.add(root);
		}
		
		return pq.poll();
	}
	
	public static void preOrder(TreeNode root, int depth) {
		if(root == null)
			return;
		for(int i=0;i<depth;i++)
			System.out.print("--");
		System.out.println(root);
		preOrder(root.left,depth+1);
		preOrder(root.right,depth+1);
	}
	public static void inOrder(TreeNode root, int depth) {
		if(root == null)
			return;
		for(int i=0;i<depth;i++)
			System.out.print("--");
		preOrder(root.left,depth+1);
		System.out.println(root);
		preOrder(root.right,depth+1);
	}
	public static void postOrder(TreeNode root, int depth) {
		if(root == null)
			return;
		for(int i=0;i<depth;i++)
			System.out.print("--");
		preOrder(root.left,depth+1);
		preOrder(root.right,depth+1);
		System.out.println(root);
	}
	
	
	public static void main(String[] args) {
		ArrayList<TreeNode> list = new ArrayList<>();
		list.add(new TreeNode("A", 1));
		list.add(new TreeNode("B", 1));
		list.add(new TreeNode("C", 3));
		list.add(new TreeNode("D", 4));
		list.add(new TreeNode("E", 5));
		list.add(new TreeNode("F", 6));
		TreeNode root = creatTree(list);
		preOrder(root,0);
		
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值