美文网首页
day17-赫夫曼树

day17-赫夫曼树

作者: Summer2077 | 来源:发表于2020-08-06 22:05 被阅读0次
    
    package com.summer.huffmantree;
    
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Collections;
    import java.util.List;
    
    public class HuffmanTree {
        public static void main(String[] args) {
            int arr[] = {13,7,8,3,29,6,1};
            Node huffmanTree = createHuffmanTree(arr);
            preOrder(huffmanTree);
        }
    
        public static Node createHuffmanTree(int arr[]){
            List<Node> nodes = new ArrayList<Node>();
            for (int i : arr) {
                nodes.add(new Node(i));
            }
            while (nodes.size()>1){
                Collections.sort(nodes);
                //取出数组中前两个节点,组成树
                Node left = nodes.get(0);
                Node right = nodes.get(1);
                Node parent = new Node(left.value+right.value,left,right);
                //删除取出的两个节点,将父节点加入
                nodes.remove(left);
                nodes.remove(right);
                nodes.add(parent);
            }
            return nodes.get(0);
        }
    
        public static void preOrder(Node node){
            if (node!=null){
                node.preOrder();
            }else {
                System.out.println("树为空");
            }
        }
    
    }
    
    //为了使Node支持排序,我们要实现Comparable接口
    class Node implements Comparable<Node>{
        int value;
        Node left;
        Node right;
    
        public Node() {
        }
    
        public Node(int value) {
            this.value = value;
        }
    
        public Node(int value, Node left, Node right) {
            this.value = value;
            this.left = left;
            this.right = right;
        }
    
        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 o) {
            //从小到大排序
            return this.value - o.value;
        }
    
        @Override
        public String toString() {
            return "Node{" +
                    "value=" + value +
                    '}';
        }
    }
    

    相关文章

      网友评论

          本文标题:day17-赫夫曼树

          本文链接:https://www.haomeiwen.com/subject/aozyrktx.html