package mylearn;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Huffmantree {
public static void main(String[] args) {
int []arr={1,2,3,4,5,6};
Huffmantree tree1=new Huffmantree();
node root= tree1.createhunffmantree(arr);
tree1.preorder(root);
}
public node createhunffmantree(int[]arr)
{
List<node> nodes=new ArrayList<>();
for(int i:arr)
{
nodes.add(new node(i));
}
while(nodes.size()>1)
{
Collections.sort(nodes);
System.out.println("curret"+nodes);
node newnode=new node(nodes.get(1).value+nodes.get(0).value);
newnode.left=nodes.get(0);//新的节点要连左右子节点
newnode.right=nodes.get(1);
nodes.remove(0);//arraylist会自动进位
nodes.remove(0);
nodes.add(newnode);
}
return nodes.get(0);//返回root用来preorder遍历
}
public void preorder(node root)
{
if(root==null)
{
return;
}
else
{
root.preorder();
}
}
}
class node implements Comparable<node>//这个接口可以给ArrayList元素的某属性排序,要在节点类
{
@Override
public String toString() {
return "node value"+this.value;
}
public int value;
public node left;
public node right;
public node(int value)
{
this.value=value;
}
public void preorder()
{
System.out.println(this);
if(this.left!=null)
{
this.left.preorder();
}
if(this.right!=null)
{
this.right.preorder();
}
}
@Override
public int compareTo(node n) {//这个要在节点类里面写
return this.value-n.value;
}
}