python 如何构建树

原创
ithorizon 7个月前 (09-30) 阅读数 48 #Python

Python中构建树的方法

在Python中,可以使用class类来定义树节点,也可以使用字典或列表来构建树。

使用class类定义树节点:

class TreeNode:
    def __init__(self, value):
        self.value = value
        self.children = []
        self.parent = None
        
    def add_child(self, child):
        child.parent = self
        self.children.append(child)

使用字典构建树:

tree = {
    "value": "root",
    "children": [
        {
            "value": "child1",
            "children": [
                {
                    "value": "grandchild1",
                    "children": []
                },
                {
                    "value": "grandchild2",
                    "children": []
                }
            ]
        },
        {
            "value": "child2",
            "children": []
        }
    ]
}

使用列表构建树:

tree = [
    {"value": "root"},
    [
        {"value": "child1"},
        [
            {"value": "grandchild1"},
            {"value": "grandchild2"}
        ]
    ],
    {"value": "child2"}
]

无论是使用class类定义节点,还是使用字典或列表构建树,都需要根据具体的需求选择适合的方式。



热门