i want to build a general tree in which a root node contains 'n' childrens and those childrens may contain other childrens.....
+4
A:
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.
Eli Bendersky
2010-03-20 10:11:15
i am unable to get started please give me a piece of code
vishnu
2010-03-20 10:13:10
@vishnu: is this enough?
Eli Bendersky
2010-03-20 10:17:24