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<TreeNode> nodes = new ArrayList<>();
for (int i = 0; i <arr.length ; i++) {
nodes.add(new TreeNode(arr[i]));
}
//给数组进行排序
Collections.sort(nodes);
while (nodes.size()>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);
}
}
数据结构和算法——赫夫曼树
最新推荐文章于 2024-07-26 10:34:47 发布