渲染二叉树数据结构的算法

问题描述 投票:0回答:1

我将一些数据组织为二叉树,其中每个节点恰好有 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()

python binary-tree render
1个回答
-1
投票

看来这段代码对我有用。 见下图。我的屏幕是 4K,这可能有所不同。所以只需为合适的尺寸添加保存代码即可。

类似的东西:

ax = plt.gca()
ax.figure.set_size_inches(30, 30)
plt.savefig("save_to_folder/file_name.png")
© www.soinside.com 2019 - 2024. All rights reserved.