What is the best way to implement a Tree Structure in python
What is the best way to implement a tree structure (generic - not binary) in python? My intuition would have the following skeleton:
cla开发者_如何学Goss TNode(self, data):
#enter things for each individual node
class TStructure(self):
#enter code for implementing nodes that reference each other.
Why not just have a class for nodes, that has a list of children nodes?
Edit to add skeleton:
class TreeNode(object):
def __init__(self, data, children=[]):
self.data = data
self.children = list(children)
def add(self, child):
self.children.append(child)
...
There's really not much to it. Every TreeNode contains a set of children (leaf nodes just have 0 children, which is about as close to a pure code implementation of the very definition of a tree leaf node as you can get). You could add methods to manipulate the order of children, but if you need that you're possibly better off just considering the children
list exposed and using the list methods directly. You could add methods like search
, but for a generic tree without known ordering constraints (like in a binary search tree, where the contents of one subtree are less than the contents of the other subtree) there's not a whole lot for it to do. You could add generator methods for traversal (with several possible traversal strategies).
If you only want the leaf nodes to have data, then you have a separate class for internal nodes and leaf nodes, where the internal nodes have children
and the leaf nodes have data
.
look into networkx and the Graph object.
see here
If this is for homework and you have to implement from scratch I'll give you the hint that you probably want a class for nodes and a class for edges...
EDIT:
You don't really need a structure class if you have a node class and an edge class something traversing the graph is just a matter of search algorithms once it is implemented.
class Node:
name=str()
class Edge:
a = Node()
b = Node()
and then string them together with __init__
functions for one of the two classes depending on how you will be loading in data.
精彩评论