Introduction and creation of Huffman Tree

Posted by Lautarox on Sat, 19 Feb 2022 10:31:56 +0100

1. Basic introduction

  • Huffman tree, alias "Huffman tree", "Huffman tree", "optimal tree" and "optimal binary tree"

  • Given n weights as n leaf nodes, a binary tree is constructed. If the weighted path length (wpl) of the tree reaches the minimum, such a binary tree is called the optimal binary tree, also known as Huffman tree. Other books are translated as Huffman tree.

  • Huffman tree is the tree with the shortest weighted path length, and the node with larger weight is closer to the root.

  • Several important concepts and examples of Huffman tree

    • Path and path length:
      • In a tree, the path between children or grandchildren that can be reached from one node down is called path.
      • The number of branches in a path is called the path length. If the specified number of layers of the root node is 1, the path length from the root node to the L-th layer node is L-1
    • Node weight and weighted path length:
      • If a node in the tree is assigned a value with a certain meaning, this value is called the weight of the node.
      • The weighted path length of a node is the product of the path length from the root node to the node and the weight of the node
    • Weighted path length of the tree: the weighted path length of the tree is specified as the sum of the weighted path lengths of all leaf nodes, which is recorded as WPL(weighted path length). The binary tree with greater weight and closer to the root node is the optimal binary tree.
    • The smallest WPL is Huffman tree

2. The idea of creating Huffman tree

  • A sequence {13,7,8,3,29,6,1} is required to be transformed into a Huffman tree

  • The steps of constructing Huffman tree;

    • Sort from small to large. Each data is a node, and each node can be regarded as the simplest binary tree
    • Take out the two binary trees with the smallest weight of the root node
    • Form a new binary tree. The weight of the root node of the new binary tree is the sum of the weight of the root node of the previous two binary trees
    • Then sort the new binary tree again according to the weight of the root node, and repeat the steps of 1-2-3-4 until all the data in the sequence are processed to get a Huffman tree

3. Code implementation

//Huffman tree creation
public class HuffmanTree {
    public static void main(String[] args) {
        int[] arr = {13, 7, 8, 3, 29, 6, 1};
        Node root = createHuffmanTree(arr);
        //test
        preOrder(root);

    }

    //Write a preorder traversal method
    public static void preOrder(Node root){
        if(root != null){
            root.preOrder();
        }else{
            System.out.println("It is an empty tree and cannot be traversed");
        }
    }

    //Method of creating Huffman tree
    /**
     *
     * @param arr You need to create an array into a Huffman tree
     * @return The root node of the created Huffman tree
     */
    public static Node createHuffmanTree(int[] arr) {
        //1. For easy operation
        //1.1 traversing arr array
        //1.2 form each element of arr into a Node
        //1.3 put Node into ArrayList
        List<Node> nodes = new ArrayList<>();

        for (int value : arr) {
            nodes.add(new Node(value));
        }

        while (nodes.size() > 1) {

            //Sort from small to large
            Collections.sort(nodes);
            System.out.println("nodes =" + nodes);

            //Take out the two binary trees with the smallest weight of the root node
            //(1) Take out the node with the smallest weight (binary tree)
            Node leftNode = nodes.get(0);
            //(2) Take out the node with the second smallest weight (binary tree)
            Node rightNode = nodes.get(1);
            //(3) Construct a new binary tree
            Node parent = new Node(leftNode.value + rightNode.value);
            parent.left = leftNode;
            parent.right = rightNode;

            //(4) Deleted binary tree from ArrayList
            nodes.remove(leftNode);
            nodes.remove(rightNode);

            //(5) Add parent to nodes
            nodes.add(parent);
        }
        //Return Huffman's root node
        return nodes.get(0);
    }

}

//Create node class
//To make the Node object support sorting Collections collection sorting
//Let Node implement Comparable interface
class Node implements Comparable<Node> {
    int value; //Node weight
    Node left; //Point to left child node
    Node right; //Point to the right child node

    //Preorder traversal
    public void preOrder() {
        System.out.println(this);
        if (this.left != null) {
            this.left.preOrder();
        }
        if (this.right != null) {
            this.right.preOrder();
        }
    }

    public Node(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }

    @Override
    public int compareTo(Node o) {
        //Indicates sorting from small to large. If sorting from large to small, take negative [- (this.value - o.value)]
        return this.value - o.value;
    }
}

Topics: Java data structure