在Dart中打印二叉树图可以通过递归遍历二叉树的方式来实现。以下是一个示例代码:
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(this.val, [this.left, this.right]);
}
void printBinaryTree(TreeNode root, [int level = 0, String branch = '']) {
if (root == null) {
return;
}
final indent = ' ' * level;
print('$indent$branch${root.val}');
if (root.left != null) {
printBinaryTree(root.left, level + 1, '├─左: ');
}
if (root.right != null) {
printBinaryTree(root.right, level + 1, '└─右: ');
}
}
void main() {
// 构造一个二叉树
final root = TreeNode(1);
final node1 = TreeNode(2);
final node2 = TreeNode(3);
final node3 = TreeNode(4);
final node4 = TreeNode(5);
final node5 = TreeNode(6);
root.left = node1;
root.right = node2;
node1.left = node3;
node1.right = node4;
node2.right = node5;
// 打印二叉树
printBinaryTree(root);
}
以上代码中,首先定义了一个TreeNode
类,用于表示二叉树的节点。节点包含一个整数值以及左右子节点。然后,定义了printBinaryTree
函数,该函数接收一个二叉树的根节点、当前层级、以及表示节点方向的前缀字符串。函数通过递归遍历二叉树,并根据层级和节点方向打印出节点值。最后,在main
函数中构造了一个示例二叉树,并调用printBinaryTree
函数进行打印。
运行以上代码,输出结果如下:
1
├─左: 2
│ ├─左: 4
│ └─右: 5
└─右: 3
└─右: 6
这样,就可以在Dart中打印二叉树图了。
注意:在答案中,我尽量避免提及具体的云计算品牌商,只给出了完整的答案内容。如有需要,可以根据实际情况添加相关品牌商的信息。
领取专属 10元无门槛券
手把手带您无忧上云