我有一个BinarySearchTree实现,它实现了接口insert
的公共Tree
方法,如下所示。
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 Tree或AVL Tree实现。我试图将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()。
调用insert方法并获取布尔结果的一个选项。检查是否为真,然后再次调用搜索方法获取节点,然后进行处理。对于这个问题还有其他更好的解决方案吗?
我还需要一个建议。我已将类Node
静态声明为仅与BST
相关。我需要另一个AVL节点类,并考虑扩展静态类Node。为了使Node在另一个包中可见,我必须声明public,以便它也可用于AVLNode。它有任何设计问题吗?
答案 0 :(得分:0)
如果insert
返回null
而非false
且找到的节点而不是true
,该怎么办?然后,您将能够一次性返回两个信息。更好的想法是返回Optional<T>
。
对于你的第二个问题,我实际上发现从另一个类的静态内部类扩展Node是很奇怪的。你说Node
只关注BST
,但是如果你需要它AVL
那不是这种情况,所以你最好有两个单独的类或一个接口/抽象类扩展BST.Node
和AVL.Node
。