1)假设您有以下抽象类定义:
abstract class AbstractBinaryTree<T> {
AbstractBinaryTree<T> parent;
AbstractBinaryTree<T> leftChild;
AbstractBinaryTree<T> rightChild;
T value;
}
以及之前未声明或实现的新方法的此类的实现:
public class BinarySearchTree<T extends Comparable<T>> extends AbstractBinaryTree<T> {
public BinarySearchTree(T pVal) {
super(pVal);
}
public Boolean isBST(){
if(leftChild != null && rightChild != null){
return (leftChild.value.compareTo(value) < 0
&& rightChild.value.compareTo(value) >= 0 )
&& ((BinarySearchTree<T>) leftChild).isBST()
&& ((BinarySearchTree<T>) rightChild).isBST();
}
else if(leftChild != null){
return leftChild.value.compareTo(value) < 0
&& ((BinarySearchTree<T>) leftChild).isBST() ;
}
else if (rightChild != null){
return rightChild.value.compareTo(value) >= 0
&& ((BinarySearchTree<T>) rightChild).isBST();
}
else{
return true;
}
}
你如何避免抛弃所有左右儿童?
2)同样假设我在AbstractBinaryTree中有以下抽象定义:
public abstract AbstractBinaryTree<T> findMinTree();
及其在BST中的实施:
/***
* @return the subtree rooted at the min value
*/
public BinarySearchTree<T> findMinTree(){
if(leftChild != null)
return (BinarySearchTree<T>) leftChild.findMinTree();
return this;
}
我该如何避免演员表演
public BinarySearchTree<T> findMinTree(){
if(leftChild != null)
return (BinarySearchTree<T>) leftChild.findMinTree();
return this;
}
还是当我给孩子打电话的时候?
BinarySearchTree<T> y = ((BinarySearchTree<T>) x.rightChild).findMinTree();
我对铸造不过敏,但在这种情况下非常重 . 在此先感谢您的回答!
2 回答
您可以使用更多的泛型,即CRTP:
而不是具有抽象超类的类引用树的结构的自身引用,我会使用
Node
类,其引用其父Node
,以及左和右子项Nodes
.AbstractBinaryTree
类将引用根Node
.那么子类不需要
Node
的类型随其自身类型而变化;BinarySearchTree
也会使用Node
.