我正在尝试使用Python的anytree库构建一个树结构。但是,我面临着在多个父级之间共享节点(特别是节点 984)的问题。这是我的代码:
from anytree import Node, RenderTree
from anytree.exporter import UniqueDotExporter
import numpy as np
# Sample data
data = np.array([
[1000., 1001., 998., 988., 980., 1003.],
[1000., 997., 1000., 979., 1002., 1000.],
[1000., 1003., 996., 1006., 1003., 1002.],
[1000., 988., 999., 984., 972., 970.],
[1000., 1000., 1032., 984., 982., 976.],
[1000., 1000., 1002., 971., 966., 963.]
])
# Recursive function to build the tree structure
def add_to_tree(tree, path):
node = tree
for value in path:
if value not in node:
node[value] = {'count': 0, 'children': {}}
node[value]['count'] += 1
node = node[value]['children']
# Initialize the tree
tree = {}
# Build the tree
for row in data:
add_to_tree(tree, row)
# Given tree structure dictionary
tree_structure = tree
# Function to create hierarchical tree nodes
def create_tree(tree_dict, parent=None):
for key, value in tree_dict.items():
node = Node(str(key), parent=parent)
create_tree(value['children'], parent=node)
# Create the tree
root = Node("1000.0")
create_tree(tree_structure[1000.0]['children'], parent=root)
# Generate the tree diagram
output_path = "full_tree.png"
UniqueDotExporter(root).to_picture(output_path)
print(f"Tree diagram saved to {output_path}")
# Display the generated tree diagram in Colab
from IPython.display import Image
Image(output_path)
但是我想要这种类型
我尝试了 Chatgpt,但不起作用。
树的定义是每个节点只能有一个父节点。您所指的结构是有向无环图(DAG)。