Árbol de Hosffman compuesto por implementación de código de matriz de tipo int

package org.structure.hoffmanTree;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 赫夫曼树
 * @author cjj_1
 * @date 2020-08-25 15:52
 */
public class Hoffman {
    
    
    public static void main(String[] args) {
    
    
        int [] arr = {
    
    13,7,8,3,29,6,1};
        Node root = hoffMan(arr);//跟节点
        System.out.println(root);
    }
    public static Node hoffMan(int[] arr){
    
    
        List<Node> nodes = new ArrayList<Node>();
        for (int value: arr){
    
    
            nodes.add(new Node(value));
        }
        while (nodes.size()>1){
    
    
            Collections.sort(nodes);
            Node leftNode = nodes.get(0);
            Node rightNode = nodes.get(1);
            Node parent= new Node(leftNode.value+ rightNode.value);
            parent.left = leftNode;
            parent.right = rightNode;
            nodes.remove(0);
            nodes.remove(0);
            nodes.add(parent);
        }

        System.out.println(nodes);
        return nodes.get(0);
    }

}
class Node implements  Comparable<Node>{
    
    
    int value;
    Node left;
    Node right;
    public Node(int value){
    
    
        this.value = value;
    }

    @Override
    public String toString() {
    
    
        return "Node{" +
                "value=" + value +
                '}';
    }
    @Override
    public int compareTo(Node o) {
    
    
        return this.value - o.value;
    }
}

Supongo que te gusta

Origin blog.csdn.net/weixin_40128696/article/details/108281843
Recomendado
Clasificación