package com.数据结构;
import java.util.ArrayList;
import java.util.Collections;
public class 哈夫曼树 {
public static void main(String[] args) {
int[] arr = new int[]{13,7,8,3,29,6,1};
ArrayList<NodeTree> list = new ArrayList<>();
for(int temp : arr){
list.add(new NodeTree(temp));
}
while(list.size()>1){
Collections.sort(list);
NodeTree n1 = list.get(0);
NodeTree n2 = list.get(1);
NodeTree n3 = new NodeTree(n1.getData()+n2.getData(),n1,n2);
list.remove(n1);
list.remove(n2);
list.add(n3);
}
new HafmTree(list.get(0)).look();
}
}
class HafmTree{
private NodeTree root;
public HafmTree() {
}
public HafmTree(NodeTree root) {
this.root = root;
}
public void look(){
if(root==null){
System.out.println("数空 无法遍历");
}else{
this.root.look();
}
}
}
class NodeTree implements Comparable<NodeTree>{
private int data;
private NodeTree Lift ;
private NodeTree Right ;
public NodeTree() {
}
public NodeTree(int data) {
this.data = data;
}
public NodeTree(int data, NodeTree lift, NodeTree right) {
this.data = data;
Lift = lift;
Right = right;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public NodeTree getLift() {
return Lift;
}
public void setLift(NodeTree lift) {
Lift = lift;
}
public NodeTree getRight() {
return Right;
}
public void setRight(NodeTree right) {
Right = right;
}
public void look(){
System.out.println(this);
if(this.getLift()!=null){
this.getLift().look();
}
if(this.getRight()!=null){
this.getRight().look();
}
}
@Override
public int compareTo(NodeTree o) {
return this.data-o.data;
}
@Override
public String toString() {
return "NodeTree{" +
"data=" + data +
'}';
}
}