开发者社区> 问答> 正文

java二叉树模板抽象化

我有两个二叉树类,分别管理着不同的数据

class bt1{
//自身业务逻辑
String s;
public String getS(){
return "godness " + s;
}
//二叉树逻辑
bt1 left;
bt1 right;
bt1 parent;
public void setLeft(bt1 l){
    this.left = l;
        l.parent = this;
}
public bt1 getLeft(){
    return left;
}
public void setRight(bt1 r){
    this.right = r;
    right.parent = this;
}
public bt1 getRight(){
    return right;
}
public bt1 getParent(){
 return parent;
}
}
class bt2{
//自身业务逻辑
int i;
public void add(){
i++;
}
//二叉树逻辑
bt2 left;
bt2 right;
bt2 parent;
public void setLeft(bt2 l){
    this.left = l;
        l.parent = this;
}
public bt2 getLeft(){
    return left;
}
public void setRight(bt2 r){
    this.right = r;
    right.parent = this;
}
public bt2 getRight(){
    return right;
}
public bt2 getParent(){
 return parent;
}
}

有没有什么办法把两个类公共的二叉树逻辑部分提出来做为父类,两个类分别继承这个父类再只需实现自己的业务逻辑,就能达成原代码功能的?

展开
收起
蛮大人123 2016-06-02 11:31:49 2298 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    其实关于二叉树的泛型实现,我觉得 树应该通用,其节点存储的数据为泛型比较理想,左右孩子和父节点的类型应该与创建的树的类型一致,
    你觉得呢?今天才看到,很抱歉

    class BTrees {
    protected BTrees<T> leftChild;
    protected BTrees<T> rightChild;
    T data;
    protected BTrees<T> parent; //非必需,半冗余数据
    public BTrees<T> getLeftChild() {
        return leftChild;
    }
    public void setLeftChild(BTrees<T> leftChild) {
        this.leftChild = leftChild;
    }
    public BTrees<T> getRightChild() {
        return rightChild;
    }
    public void setRightChild(BTrees<T> rightChild) {
        this.rightChild = rightChild;
    }
    public T getData() {
        return data;
    }
    public void setData(T data) {
        this.data = data;
    }
    public BTrees<T> getParent() {
        return parent;
    }
    public void setParent(BTrees<T> parent) {
        this.parent = parent;
    }
    }
    2019-07-17 19:24:27
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载