我正在学习数据结构,我正在构建一个AVL树类。我想通过在一个字符串中保存元素来遍历树。我已经构建了三个函数,在控制台上递归地遍历树上的{inorder、preorder、postorder}。我想知道如何修改代码,将结果加载到字符串,而不是控制台。
我会在下面张贴邮购代码:
void printPostorder(Node root) { // prints the tree in post order left right root
if (root == null)
return;
printPostorder(root.left);
printPostorder(root.right);
System.out.print(root.element + " ");
}发布于 2022-06-10 18:20:33
我不知道你是如何制作你的printPostorder或printPostorder的,但是你可以用一个字符串生成器
StringBuilder str = new StringBuilder();
// you might want to do this recursively or with a loop though
str.append(printPostorder(root.left).toString);
str.append(printPostorder(root.right).toString);另外,有关更有趣的内容,请参见How to print binary tree diagram in Java?
https://stackoverflow.com/questions/72577063
复制相似问题