pythonooptreeclass-methodinstance-method

Root node operations in tree data structures


Need a way to indicate/enforce that certain methods can only be done on the root Node of my tree data structure. I'm working in Python 2.x

I have a class, Node, which I use in conjunction with another class, Edge, to build a tree data structure (edges are letters and nodes are words, in this case).

Some methods in Node are needed for every instance of the Node, like get_word, which runs backwards through the tree to determine the word being represented by that Node. But other Node operations, like load_word_into_tree, seem more like a class methods -- they operate on the entire tree. Furthermore, the way I have structured the that call, it requires the root node and the root node only as its input. If it is called on any other node, it'll totally mess up the tree.

I see two options:

Any help on where and how to implement this function would be greatly appreciated.


Solution

  • Make a Tree subclass of Node and add the tree-only methods on that class instead.

    Then make your root an instance of Tree, the rest of your graph uses Node instances.