java 函数是否可以深度复制表达式树(包括其父层次结构)?

9fkzdhlc  于 5个月前  发布在  Java
关注(0)|答案(1)|浏览(63)

我想深度复制一个表达式树。我知道传统的方法,它在大多数情况下都有效。下面是表达式树的基本版本:

public class Expression {
    public Expression left;
    public Expression right;
    public Expression parent;
    public String middle;

    public Expression(Expression left, String middle, Expression right) {
        this.left = left;
        this.right = right;
        this.middle = middle;

        if (left != null) {
            left.parent = this;
        }

        if (right != null) {
            right.parent = this;
        }
    }

    public void setLeft(Expression left) {
        this.left = left;
        if (left != null) {
            left.parent = this;
        }
    }

    public void setRight(Expression right) {
        this.right = right;
        if (right != null) {
             right.parent = this;
        }
    }}

字符串
以下是深度复制的传统方法:

public Expression copy() {
    Expression leftCopy = (left != null) ? left.copy() : null;
    Expression rightCopy = (right != null) ? right.copy() : null;
    
    return new Expression(leftCopy, operator, rightCopy, null);
}


现在这个工作很好,但我想要另一个深复制功能(copyFull)它也复制父层次结构。当前的深拷贝只复制表达式,并使其成为根,而不管它是否实际上是根。现在我将如何做一个完整的深拷贝函数,它将确保复制整个结构,包括父层次结构,并且该函数应返回一个表达式示例,它调用了copyFull()函数。我相当肯定这个新的深度复制函数将使用以前的一个。示例用法:Expression rightRightCopy = originalExpression.right.right.copyFull();Expression originalExpressionCopy = rightRightCopy.parent.parent;

ekqde3dh

ekqde3dh1#

嗯,在玩了一会儿之后,我找到了解决办法。我不确定这是不是最干净的方法,但它能完成工作。

public Expression copyFull() {
    return copyFull(this);
}

private Expression copyFull(Expression reference) {
    if (reference.isRoot()) return copy()

    Expression parent = reference.parent;
    Expression current = this == reference ? copy() : this;
    Expression newParent = null;

    if (reference.isLeftChildOf(parent)) {
        Expression rightCopy = parent.right != null? parent.right.copy() : null;
        newParent = new Expression(current, middle, rightCopy);
    } else {
        Expression leftCopy = parent.left != null? parent.left.copy() : null;
        newParent = new Expression(leftCopy, middle, current);
    }
    
    newParent.parent = newParent.copyFull(parent).parent;
    return current;
}

字符串

相关问题