数据结构-树型实现哈夫曼树(Java)

 哈夫曼树

哈夫曼树,第一行输入一个数n,表示叶结点的个数,第二行输入各个叶子结点的权值。

需要用这些叶结点生成哈夫曼树,题目需要输出哈夫曼树的带权路径长度(WPL)。

输入格式:

第一行输入一个数n,第二行输入n个叶结点的权值(叶结点权值不超过10002<=n<=1000)。

输出格式:

在一行中输出WPL值。

输入样例:

5
1 2 2 5 9

输出样例:

37

 首先我们先获取从键盘中输入的数值,然后再将所获取的数值放进ArrayList中,最后调用hafu()方法,代码如下所示:

Scanner sc = new Scanner(System.in);

        while (sc.hasNextInt()){
            int n = sc.nextInt();                       //需要多少个叶子结点

            ArrayList<Integer> list = new ArrayList<>();
            for (int i = 0; i < n ; i++) {
                int x = sc.nextInt();                   //叶子结点的数值
                list.add(x);
            }
            System.out.println(hafu(list));
        }

hafu()方法首先将ArrayList列表进行排序,如果list的大小等于两个的时候直接返回列表的第一个数和第二个数,最后再通过return统计总数。代码如下所示:

 public static int hafu(ArrayList<Integer> list) {
        Collections.sort(list);                                 //list列表可以通过 Collections.sort进行排序
        if(list.size() == 2) return list.get(0) + list.get(1);
        int a = list.remove(0);
        int b = list.remove(0);
        int n = a + b;
        list.add(n);
        return a + b + hafu(list);                              //进行统计
    }

流程图如下图所示:

结果图:

 

最后完整的代码如下所示:

import java.util.*;

public class HuFu {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        while (sc.hasNextInt()){
            int n = sc.nextInt();                       //需要多少个叶子结点

            ArrayList<Integer> list = new ArrayList<>();
            for (int i = 0; i < n ; i++) {
                int x = sc.nextInt();                   //叶子结点的数值
                list.add(x);
            }
            System.out.println(hafu(list));
        }
    }

    public static int hafu(ArrayList<Integer> list) {
        Collections.sort(list);                                 //list列表可以通过 Collections.sort进行排序
        if(list.size() == 2) return list.get(0) + list.get(1);
        int a = list.remove(0);
        int b = list.remove(0);
        int n = a + b;
        list.add(n);
        return a + b + hafu(list);                              //进行统计
    }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LSuccess

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值