What is the best way to implement a tree structure (generic – not binary) in python? My intuition would have the following skeleton:
class 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:
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
childrenlist exposed and using the list methods directly. You could add methods likesearch, 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
childrenand the leaf nodes havedata.