python - 实现一个 child 和 parent 可以互相引用的树

标签 python tree

来自 http://cbio.ufs.ac.za/live_docs/nbn_tut/trees.html

Let's create a python class to represent a tree. We need some way to store data in a node, and some way to indicate any child nodes, or subtrees.

class node(object):
    def __init__(self, value, children = []):
        self.value = value
        self.children = children

Whoa! That seems way too easy... but believe it or not, it does the job. Let's use our new class to store our family tree...

tree = node("grandmother", [
    node("daughter", [
        node("granddaughter"),
        node("grandson")]),
    node("son", [
        node("granddaughter"),
        node("grandson")])
    ]);

我希望能够获得每个 node 实例的子节点和父节点,所以我认为我需要同时定义其父节点和子节点

class node(object):
    def __init__(self, value, children = [], parent = []):
        self.value = value
        self.children = children
        self.parent = parent

但问题是每个节点在其每个子节点和父节点中都会有一个副本。如果我更改它的值,我将不得不更改其副本中的所有值。在 C++ 中,没有这样的问题,因为我们可以通过将指向其子节点和父节点的指针仅存储在节点中来引用节点的子节点和父节点。我想知道如何在 Python 中实现这样的树?谢谢。

最佳答案

您可以在节点构造函数中分配 child 的 parent :

class node(object):
    def __init__(self, value, children = None):
        self.value = value
        self.children = children or []
        self.parent = None
        for child in self.children:
            child.parent = self

关于python - 实现一个 child 和 parent 可以互相引用的树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25437376/

相关文章:

python - 在Python中划分列表中的元素以标准化数据

python - 组合元组的二维列表,然后在 Python 中对它们进行排序

c++ - 实现通用树

algorithm - 树中所有边不相交路径的列表

algorithm - 如何快速获得树上所有叶子的所有 parent ?

java - Java 中的二叉树 - 为什么我的树中有一个 "empty"节点(带有空白字符串)?

javascript - extjs3.4 : How to access items in a panel that do not have id/itemId

python - 在 Django 中计算多列并排序

python - 从 cx_Oracle 内部使用 SQL*PLUS COPY?

python - 在 python : how to split newlines while ignoring newline inside quotes 中解析字符串