使用java的二叉树的toString方法

时间:2016-10-07 03:05:34

标签: javascript java binary-tree

预期(A (D () ()) (B (C () ()) ()))

得到A(D() ()) (B(C() ()) ())

我输了第一个和最后一个支架。

private String toString(BinaryNode curr) {

    String str = "";
    if(curr == null) {
        return str;
    } else{
    str += curr.value;
    str += "(" + toString(curr.left) + ") (" + toString(curr.right) + ")";
    }

    return str;
}

如果我更改了代码,我得到了(A((D() ())) ((B((C() ())) ())))

private String toString(BinaryNode curr) {

    String str = "";
    if(curr == null) {
        return str;
    } else{
    str += curr.value;
    str += "(" + toString(curr.left) + ") (" + toString(curr.right) + ")";
    }

    return "(" + str + ")";
}

1 个答案:

答案 0 :(得分:0)

您需要确定代码的哪一部分由括号括起。返回的人似乎做了这个工作:

private String toString(BinaryNode curr) {

    String str = "";
    if(curr == null) {
        return str;
    } else{
        str += curr.value+" ";
        str += toString(curr.left) + toString(curr.right);
    }

return "(" + str + ")";

}