【问题标题】:Java Binary Search Tree - Compute the length of a path to a nodeJava Binary Search Tree - 计算节点路径的长度
【发布时间】:2014-12-03 16:08:15
【问题描述】:

使用 Java 的 TreeMap 实现,如何计算到树中指定节点的路径长度?我的意思是计算在二叉搜索树中搜索节点时执行的比较次数。

【问题讨论】:

  • 可能不会,因为您只能访问数据而不是直接访问节点。
  • 是平衡树。所以它是aprox。 log2(size_of_map)

标签: java binary-search treemap


【解决方案1】:

TreeMap has a constructor 将 Comparator 作为参数。比较器用于对存储在映射中的键进行排序。如果您真的想“计算执行的比较次数”,您可以编写一个检测比较器来计算它被调用的次数。

public class StringComparator implements Comparator<String> {
    private int count = 0;

    @Override
    public int compare(String o1, String o2) {
        ++count;
        return o1.compareTo(o2);
    }

    public int getCount() { return count; }
    public void reset() { count = 0; }

    public static void main(String[] args) {
        StringComparator sc = new StringComparator();
        TreeMap<String, String> map = new TreeMap<>(sc);
        map.put("foo", "one");
        System.out.println("foo took " + sc.getCount() + " comparisons");
        sc.reset();
        map.put("bar", "two");
        System.out.println("bar took " + sc.getCount() + " comparisons");
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 2021-05-05
    • 2021-06-18
    • 2020-11-12
    • 1970-01-01
    • 2018-09-29
    相关资源
    最近更新 更多