数据结构和算法——赫夫曼树

package com.demo.calculate;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import com.demo.calculate.bean.TreeNode;

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

public class HuffManActivity extends AppCompatActivity {
    private int[] arr = new int[]{3,5,7,25,12,14,29,27};
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_huffman);
        findViewById(R.id.btn_hufuMan).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TreeNode huffManTree = createHuffManTree();
                Log.i("tag",huffManTree.getValue()+"=====huffManTree======");
            }
        });
    }
    /**
     * 创建赫夫曼树
     */
    private TreeNode createHuffManTree() {
        List nodes = new ArrayList<>();
        for (int i = 0; i 1){
            TreeNode nodeLeft = nodes.get(0);
            TreeNode nodeRight = nodes.get(1);
            TreeNode parent = new TreeNode(nodeLeft.getValue()+nodeRight.getValue());
            //移除最小的两个元素
            nodes.remove(nodeLeft);
            nodes.remove(nodeRight);
            //添加新的元素
            nodes.add(parent);
        }
        return nodes.get(0);
    }
}

你可能感兴趣的:(数据结构和算法——赫夫曼树)