我有一个像这样的二叉树节点:
class BinaryTreeNode<T> {
BinaryTreeNode(this.value, {this.leftChild, this.rightChild});
T value;
BinaryTreeNode? leftChild;
BinaryTreeNode? rightChild;
}我想添加一个toString方法,这样我就可以直观地表示二叉树的内容。
这是this Java question的Dart版本。我能够将其中一个答案移植到那里,所以我将其添加到下面。
发布于 2021-10-25 04:16:34
以下是this answer的修改版本
class BinaryTreeNode<T> {
BinaryTreeNode(this.value, {this.leftChild, this.rightChild});
T value;
BinaryTreeNode<T>? leftChild;
BinaryTreeNode<T>? rightChild;
@override
String toString() {
final out = StringBuffer();
rightChild?._buildTree(out, true, '');
out.writeln(value);
leftChild?._buildTree(out, false, '');
return out.toString();
}
void _buildTree(StringBuffer out, bool isRight, String indent) {
rightChild?._buildTree(out, true, indent + (isRight ? ' ' : '│ '));
out
..write(indent)
..write(isRight ? '┌─── ' : '└─── ')
..writeln(value);
leftChild?._buildTree(out, false, indent + (isRight ? '│ ' : ' '));
}
}如果你像这样构建一棵树:
void main() {
final tree = BinaryTreeNode('D',
leftChild: BinaryTreeNode('A'),
rightChild: BinaryTreeNode(
'R',
leftChild: BinaryTreeNode('T'),
rightChild: BinaryTreeNode('Fun'),
));
print(tree);
}输出如下所示:
┌─── Fun
┌─── R
│ └─── T
D
└─── A请随意修改我的答案,使其代码更简单。我觉得toString方法可以简化,不需要重复这么多代码。
来自lrn的建议解决方案
下面的解决方案效率更高,因为我们避免了在遍历树结构时创建中间字符串对象。感谢lrn提出了这种方法:
class BinaryTreeNode<T> {
BinaryTreeNode(this.value, {this.leftChild, this.rightChild});
T value;
BinaryTreeNode<T>? leftChild;
BinaryTreeNode<T>? rightChild;
@override
String toString() {
final out = StringBuffer();
final indents = <String>[];
rightChild?._buildTree(out, true, indents);
out.writeln(value);
leftChild?._buildTree(out, false, indents);
return out.toString();
}
void _buildTree(StringBuffer out, bool isRight, List<String> indents) {
if (rightChild != null) {
indents.add(isRight ? ' ' : '│ ');
rightChild!._buildTree(out, true, indents);
indents.removeLast();
}
out
..writeAll(indents)
..write(isRight ? '┌─── ' : '└─── ')
..writeln(value);
if (leftChild != null) {
indents.add(isRight ? '│ ' : ' ');
leftChild!._buildTree(out, false, indents);
indents.removeLast();
}
}
}https://stackoverflow.com/questions/69702826
复制相似问题