【问题标题】:Returning a String of values from a tree从树中返回一个字符串值
【发布时间】:2020-10-06 00:21:54
【问题描述】:

好的,我想用中序、前序和后序遍历一棵树。我得到了遍历树的正确算法,但我需要以"Node1 Node2 Node3" 的形式返回字符串,但我有"Node1Node2Node3"。这是我的预购代码:

public String PreOrder() {
        /* TODO: Implement */
        StringBuilder string = new StringBuilder();
        preorderRecursive(string, root);
        return string.toString();
    }
    public StringBuilder preorderRecursive(StringBuilder string, Node current){
        if (current != null) {
        string.append(current.key);
        preorderRecursive(string, current.left);
        preorderRecursive(string, current.right);
        }
        return string;
    }

我收到错误org.junit.ComparisonFailure: expected:<3[ 1 2 8 4 5 7 9 ]10> but was:<3[1284579]10>

【问题讨论】:

  • 预期输出和实际输出有什么区别?数字之间的空格?您可以轻松添加这些内容。
  • 是数字之间的空格,但是当我输入 string.append(current.key + " ") 我得到错误:org.junit.ComparisonFailure: expected: 但是是:(注意括号之间的空格)

标签: java string data-structures tree preorder


【解决方案1】:

只需在 stringBuilder 中添加一个空格,

if (current != null) {
   string.append(current.key).append(" ");
   ...

【讨论】:

  • 我已经有了这个想法,但后来我得到了错误:org.junit.ComparisonFailure: expected: 但是是:(注意括号之间的空格)
  • 如果要删除最后的空格,请执行此操作 `string.setLength(string.length()-1); ` 在你的 PreOrder() 方法中,就在返回之前
猜你喜欢
  • 2020-10-23
  • 2012-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-21
  • 2014-10-20
  • 1970-01-01
  • 2019-12-28
相关资源
最近更新 更多