java 打印级别顺序二进制搜索树格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13186941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Printing Level Order Binary Search Tree Formatting
提问by ILostMySpoon
I have implemented the following code to print a binary search tree in level order.
我已经实现了以下代码以按级别顺序打印二叉搜索树。
public void printLevelOrder(int depth) {
for (int i = 1; i <= depth; i++) {
printLevel(root, i);
}
}
public void printLevel(BinaryNode<AnyType> t, int level) {
if (t == null) {
return;
}
if (level == 1) {
System.out.print(t.element);
} else if (level > 1) {
printLevel(t.left, level - 1);
printLevel(t.right, level - 1);
}
}
I am trying to figure out how to improve my code to have it print out in a certain format.
我想弄清楚如何改进我的代码以使其以某种格式打印出来。
As an example, given a tree
例如,给定一棵树
1
/ \
2 3
/ / \
4 5 6
Currently it prints like so:
目前它打印如下:
123456
I am looking for it to print as follows:
我正在寻找它打印如下:
Level 0: 1
Level 1: 2 3
Level 2: 4 5 6
回答by Aziz
Instead of printing the values immediately inside the recursive function calls, use strings to hold the values. This will make it easier to manipulate the output.
不要在递归函数调用中立即打印值,而是使用字符串来保存值。这将使操作输出更容易。
public void printLevelOrder(int depth) {
for (int i = 1; i <= depth; i++) {
System.out.print("Level " + (i-1) + ": ");
String levelNodes = printLevel(root, i);
System.out.print(levelNodes + "\n");
}
}
public String printLevel(BinaryNode<AnyType> t, int level) {
if (t == null) {
return "";
}
if (level == 1) {
return t.element + " ";
} else if (level > 1) {
String leftStr = printLevel(t.left, level - 1);
String rightStr = printLevel(t.right, level - 1);
return leftStr + rightStr;
}
else // you need this to get it to compile
return "";
}
Output:
输出:
Level 0: 1
Level 1: 2 3
Level 2: 4 5 6