给每个节点的遍历打印了深度
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);
}
}