I have several different types of tree nodes, each of which may have anywhere from 0 to 5 children. I'm trying to figure out an algorithm to generate all possible trees of depth <= N. Any help here? I'm having trouble figuring out how to recursively walk the tree given that each change I make to a node may expose new subtrees (or remove old ones).
相关问题
- Highlight parent path to the root
- Avoid overlapping of nodes in tree layout in d3.js
- Get path of node in tree
- Haskell - How to create a mapTree function based o
- How to solve “The data cannot have more levels tha
相关文章
- Generate Fortran subroutine with SymPy codegen for
- x86 instruction encoding tables
- Problems with Promote() using the red-black tree i
- Access nested children in xml file parsed with Ele
- Haskell label a binary tree through depth-first in
- Recursive post order tree traversal without creati
- .NET Databinding - Custom DataSource for a recursi
- Traversing an object getting the key and all paren
If the only difference between node types is the number of children, then generating every possible tree with only the node type with the greatest number of children will also generate every possible tree for any combination of nodes having equal or fewer children.
That's sort of a mouthful...
Put another way, if 5 children is the maximum, then some of the possible trees made of only 5-children nodes will have nodes that have, for example, two actual children, and three null pointers. This is practically the same as having a node with only two children.
You could create a function containing a for loop which adds the elements to a multidimensional array and calls that function again, until the tree is complete. I cannot provide examples since I don't know which language you prefer.
Here's a Python program I wrote up that I think does what you're asking. It'll return all of the possible trees given a starting node. Essentially, it boils down to a trick with bit manipulation: if a node has 5 children, then there are 25 = 32 different possible subtrees as each child can independently be present or not present in a subtree.
Code:
Here's a graphical representation of the test tree:
And here's the output from running the program:
If you'd like I could translate this into a different language. You didn't specify so I used Python; the code would be a bit more verbose in Java or C++ or whatever since I took advantage of Python's list comprehensions in a big way.
http://books.google.co.uk/books?id=56LNfE2QGtYC&pg=PA23&lpg=PA23&dq=hansel%27s+algorithm&source=bl&ots=vMbfFj-iZi&sig=E0cI5XhVZ3q1Lg9eAJ_1zYQm53U&hl=en&ei=8udlStuKJ8ehjAfJ1ZSUAQ&sa=X&oi=book_result&ct=result&resnum=1