实现一个孩子和父母可以相互参考的树 [英] Implement a tree where children and parents can refer to each other

查看:23
本文介绍了实现一个孩子和父母可以相互参考的树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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 实例的子节点和父节点,所以我想我需要定义它的父节点和子节点

I would like to be able to get both the children and parent of each node instance, so I think I would need to define both its parent and its children

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

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

But the problem is that there will be a copy of each node inside each of its children and parent. If I change its value, I will have to change all the values in its copies. In C++, there is no such a problem , because we can refer to the children and parent of a node by storing the pointers to its children and parent only in it. I wonder how such a tree can be implemented in Python? Thanks.

推荐答案

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

You can assign parents of children in the node constructor:

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

这篇关于实现一个孩子和父母可以相互参考的树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆