【发布时间】:2015-01-03 07:10:35
【问题描述】:
我有一个 BinarySearchTree 实现,它实现了接口 Tree 的公共 insert 方法,如下所示。
public class BinarySearchTree<T extends Comparable<T>> implements Tree<T> {
public boolean insert(T value) {
Node<T> nodeInserted = insertValue(value); //call private method to insert.
return (nodeInserted != null);
}
protected Node<T> insertValue(T value) {
//insert the node and then return it.
}
public Node<T> search(T value) {
//search and return node.
}
//Node class for BST
public static class Node<T extends Comparable<T>> {
// Fields and getters and setters.
}
}
这个想法是其他派生类(例如 AVL)树将覆盖方法 insertValue 为: `
public class AVLTree<T extends Comparable<T>> extends BinarySearchTree<T> {
@Override
protected Node<T> insertValue(T id) {
//specific code to insert node in AVL
}
// AVL Node
public static class AVLNode<T extends Comparable<T>> extends Node<T> {
// Fields and getters/ setters
}
}
现在我有了另一个类 TreeMap,可以使用 RB 树或 AVL 树来实现。我正在尝试将 AVL 的代码重用为:
public class TreeMap<K extends Comparable<K>, V> implements Map<K,V> {
private AVLTree<K> tree = null;
@Override
public V put(K key, V value) {
//Here is the problem.
}
}
问题是:我想在 AVL 树中插入 key 属性作为节点,然后需要获取插入的节点并做一些处理工作。我既无法覆盖也无法获取 AVLTree 类的 insertValue()。
调用插入方法并获得布尔结果的一个选项。检查是否为真然后再次调用搜索方法获取节点然后进行处理。对于这个问题还有其他更好的解决方案吗?
我还需要一个建议。我已将 Node 类声明为静态类,仅与 BST 相关。我需要另一个用于 AVL 的节点类,并考虑扩展静态类 Node。为了使 Node 在另一个包中可见,我必须声明 public 以便它也可用于 AVLNode。它有任何设计问题吗?
【问题讨论】:
标签: java performance tree binary-search-tree