一般的树实现? [英] A general tree implementation?
本文介绍了一般的树实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想构建一个通用树,其根节点包含'n'个子节点,而这些子节点可能包含其他子节点......
解决方案
Python 中的树非常简单.创建一个包含数据和子项列表的类.每个孩子都是同一个类的一个实例.这是一个一般的n-nary树.
类节点(对象):def __init__(self, data):self.data = 数据self.children = []def add_child(self, obj):self.children.append(obj)
然后互动:
<预><代码>>>>n = 节点(5)>>>p = 节点(6)>>>q = 节点(7)>>>n.add_child(p)>>>n.add_child(q)>>>n.儿童[<__main__.Node 对象在 0x02877FF0>,<__main__.Node 对象在 0x02877F90>]>>>对于 n.children 中的 c:... 打印 c.data...67>>>这是一个非常基本的骨架,没有抽象或任何东西.实际代码将取决于您的特定需求 - 我只是想表明这在 Python 中非常简单.
I want to build a general tree whose root node contains 'n' children, and those children may contain other children.....
解决方案
A tree in Python is quite simple. Make a class that has data and a list of children. Each child is an instance of the same class. This is a general n-nary tree.
class Node(object):
def __init__(self, data):
self.data = data
self.children = []
def add_child(self, obj):
self.children.append(obj)
Then interact:
>>> n = Node(5)
>>> p = Node(6)
>>> q = Node(7)
>>> n.add_child(p)
>>> n.add_child(q)
>>> n.children
[<__main__.Node object at 0x02877FF0>, <__main__.Node object at 0x02877F90>]
>>> for c in n.children:
... print c.data
...
6
7
>>>
This is a very basic skeleton, not abstracted or anything. The actual code will depend on your specific needs - I'm just trying to show that this is very simple in Python.
这篇关于一般的树实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文