你们能用这种方法帮助我吗? 我之前有一个返回,但它没有工作
private String leafNodes(TreeNode root, String leafs){
if (root.isLeaf()) {
leafs += Integer.toString(root.getData());
}
else {
if(root.getLeft() != null) {
leafs += leafNodes(root.getLeft(), leafs);
}
if (root.getRight() != null) {
leafs += leafNodes(root.getRight(), leafs);
}
return leafs;
}
return leafs;
}
答案 0 :(得分:1)
问题是您将leafs
传递给子节点,然后将结果添加到当前字符串中,以便在返回的字符串中多次出现相同的叶子。你可以这样修理它:
private String leafNodes(TreeNode root){
String leaves = "";
if (root.isLeaf()) {
leaves = Integer.toString(root.getData());
}
else {
if(root.getLeft() != null) {
leaves += leafNodes(root.getLeft());
}
if (root.getRight() != null) {
leaves += leafNodes(root.getRight());
}
}
return leaves;
}