gpt4 book ai didi

java - 从树中返回值的字符串

转载 作者:行者123 更新时间:2023-12-01 16:15:23 25 4
gpt4 key购买 nike

好吧,我想用中序、前序和后序遍历一棵树。我得到了遍历树的正确算法,但我需要以 "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>

最佳答案

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

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

关于java - 从树中返回值的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62407707/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com