【问题标题】:Implement a tree where children and parents can refer to each other实现一棵树,孩子和父母可以互相参考
【发布时间】:2014-08-21 23:14:15
【问题描述】:

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

让我们创建一个 python 类来表示一棵树。我们需要一些方法来 将数据存储在节点中,并以某种方式指示任何子节点,或者 子树。

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

哇!这似乎太容易了......但不管你信不信,它确实做到了 工作。让我们使用我们的新类来存储我们的家谱...

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 中实现这样的树?谢谢。

【问题讨论】:

    标签: python tree


    【解决方案1】:

    您可以在节点构造函数中分配孩子的父母:

    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 没有指针或引用。那么我们一般如何才能达到同样的效果呢?
    • @蒂姆。 Python 中的每个变量都是对对象的引用。
    • @Tim See this question
    • 好的,我比我更喜欢这个答案,所以我删除了我的答案。
    • 这里在构造函数中使用children=[]意味着如果以后添加任何没有子节点的节点将共享子节点。
    【解决方案2】:
    class node(object): 
      def __init__(self, value, children = []): 
        self.value = value 
        self.children = children
    
    tree = [node("grandmother", [ node("daughter", [ node("granddaughter"), node("grandson")]), node("son", [ node("granddaughter"), node("grandson")]) ])];
    
    def familyValues(targetName, siblings = []):
      family = []
      for sibling in siblings:
        if sibling.value == targetName:
          family.append(sibling)
          family = family + sibling.children
          break
        else:
          children = familyValues(targetName, sibling.children)
          if len(children) > 0:
            children.append(sibling)
            family = children
    
      return family
    
    myFamily = familyValues('daughter', tree)
    for sibling in myFamily:
      print(sibling.value)
    

    在 python 中没有对象的副本,除非你明确地克隆它们

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-09
      • 2023-03-18
      • 2015-03-02
      相关资源
      最近更新 更多