Python 樹結構是指樹形結構,是一種非線性數據結構,在計算機科學中常被用于模擬層級關系,如文件系統目錄層級關系,HTML DOM的節點層級關系等等。Python中的樹可視化一般是基于Matplotlib庫或Plotly庫完成的。
import matplotlib.pyplot as plt class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None def plot_tree(root): def height(root): if not root: return 0 return max(height(root.left), height(root.right)) + 1 def traverse(root, pos, h, idx, result): if not root: return gap = 2 ** (h - idx - 1) result[idx][pos] = str(root.val) if root.left: result[idx + 1][pos - gap] = '/' traverse(root.left, pos - gap * 2, h, idx + 2, result) if root.right: result[idx + 1][pos + gap] = '\\' traverse(root.right, pos + gap * 2, h, idx + 2, result) h = height(root) w = 2 ** (h-1) * 3 result = [[''] * w for _ in range(h)] traverse(root, w // 2, h-1, 0, result) for row in result: print(''.join(row)) plt.axis('off') plt.imshow([[0]], cmap='gray') for i in range(h): for j in range(w): if result[i][j]: plt.text(j, i, result[i][j], fontsize=18, ha='center', va='center') plt.show() tree = TreeNode(1) tree.left = TreeNode(2) tree.right = TreeNode(3) tree.left.left = TreeNode(4) tree.left.right = TreeNode(5) tree.right.left = TreeNode(6) plot_tree(tree)
以上代碼是基于Matplotlib庫實現的樹可視化。其核心是將樹轉化為字符串矩陣,然后通過Matplotlib庫實現矩陣可視化。通過此代碼,我們可以將一顆樹按照一定的格式展示在控制臺上。如果想要實現網頁中的樹結構可視化,可以嘗試使用Plotly庫等其他的可視化庫。