我将一些数据组织为二叉树,其中每个节点恰好有 0 或 2 个子节点。 我正在寻找一种算法,允许我将这棵树渲染成图像(首选 PNG)。 我想将节点呈现为一个框,其中包含一些表示节点所表示数据的多行文本。 所有节点都应该有相同的边界框并且渲染应该像this.
一样对齐我会很感激 python 解决方案,但我不限于它。
我确实用
matplotlib
(由 ChatGPT 生成)尝试过这种解决方案,但无法调整每个节点之间的间隙,因此它们不会相互重叠。
import matplotlib.pyplot as plt
BOX_WIDTH = 2
BOX_HEIGHT = 2
class Node:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def get_content(self):
box_props = dict(boxstyle='square', facecolor='white', edgecolor='black')
value = self.val
lines = ['Line 1asdasdasd', 'Line 2', 'Line 3']
text = '\n'.join(lines)
content = dict(value=value, text=text, box_props=box_props)
return content
def plot_tree(node, x, y, parent_x=None, parent_y=None, x_offset=1., y_offset=1.):
# Get node content
if node is None:
return
content = node.get_content()
# Draw box containing lines of text
r = plt.text(x, y, content['text'], bbox=content['box_props'], ha='center', va='center')
# Plot edge
if parent_x is not None and parent_y is not None:
plt.plot([parent_x, x], [parent_y, y], linewidth=1, color='black')
# Plot left and right subtree with adjusted coordinates
plot_tree(node.left, x - x_offset, y - y_offset, x, y, x_offset / 2, y_offset)
plot_tree(node.right, x + x_offset, y - y_offset, x, y, x_offset / 2, y_offset)
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
root.right.right.left = Node(2)
root.right.right.right = Node(3)
root.right.right.left.left = Node(4)
root.right.right.left.right = Node(5)
root.right.right.right.left = Node(6)
root.right.right.right.right = Node(7)
plt.figure()
plot_tree(root, 0, 0)
# plt.axis('off')
plt.show()