Creating all binary trees with unique permutations

蹲街弑〆低调 提交于 2020-01-04 02:48:27

问题


I have a rather silly question which I swear is not homework. For the life of me, I cannot remember whether I ever studied an algorithm to do this, and my mind's eye / creativity is failing me.

I have a list of unique nodes. I need to generate all unique permutations of a binary tree containing these nodes. Chirality, in case you are wondering, matters; a binary tree flipped on its axis (left / right) is not the same.

Some background information, in case you are wondering: it's for a seed creation algorithm for an evolutionary program, so a large number of tiny seeds is fine.

Edit: Clarification of uniqueness

Examples:

This:
  1
 / \
2   3

Is not the same as this:
  1
 / \
3   2

Nor is it the same as this:

    1
   /
  3
 /
2   

Nor this:

1
 \
  2
   \
    3

回答1:


Eric Lippert has a relevant post here (actually the start of a series of posts). The key bit is this recursive LINQ method:

static IEnumerable<Node> AllBinaryTrees(int size)
{
    if (size == 0)
        return new Node[] { null };
    return from i in Enumerable.Range(0, size)
           from left in AllBinaryTrees(i)
           from right in AllBinaryTrees(size - 1 - i)
           select new Node(left, right);
}

This gets all possible binary tree structures of a given size.

I think that if you take (a) all permutations of your list of nodes, and (b) Eric's list of all tree structures, and perform a "cross product" of the two (where you assign your permuted nodes to the nodes in a structure left-to-rightin some consistent order) you should get all the trees you want.

E.g. for 3 items

Permutations                        Tree structures
123  132                                 .   .    .    .    .        
213  231                               ./  ./   ./ \.   \.   \.
312  321                             ./     \.         ./      \.

Result
:      1   1    1    1    1             1   1    1    1    1      
:    2/  2/   2/ \3   \2   \2         3/  3/   3/ \2   \3   \3
:  3/     \3         3/      \3     2/     \2         2/      \2

:      2   2    2    2    2             2   2    2    2    2      
:    1/  1/   1/ \3   \1   \1         3/  3/   3/ \1   \3   \3
:  3/     \3         3/      \3     1/     \1         1/      \1

:      3   3    3    3    3             3   3    3    3    3      
:    1/  1/   1/ \2   \1   \1         2/  2/   2/ \1   \2   \2
:  2/     \2         2/      \2     1/     \1         1/      \1

This would be harder if you didn't care about chirality.

(Generating permutations of your input nodes, and assigning a permutation to one of Eric's structures, should be fairly trivial... right?)



来源:https://stackoverflow.com/questions/11449825/creating-all-binary-trees-with-unique-permutations

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!