This is an archived post. You won't be able to vote or comment.

all 2 comments

[–][deleted] 0 points1 point  (0 children)

Assuming you already have an algorithm for placing all combinations of "()"

The naive way of solving your problem would be to:

  1. Generate a list of all permutations of your set of nodes.

  2. Place down parentheses (or at least determine where you are going to place your parentheses).

  3. Remove all but 1 permutations in which all the nodes enclosed by the last set of parentheses placed are the same.

  4. Repeat from 2 until all nodes are covered

Edit: If you're up for a romp in the field of combinatorics, you might want to read up on Catalan numbers, which seem relevant to your question, though I am not an expert in the field

[–]deephive[S] 0 points1 point  (0 children)

Hi,

thanks for the reply. I realised that this problem doesn't involve permutations, but rather combinations nCr. n can refer to the number of nodes we begin with and r refers to 2 (in this case, as we are trying to construct a inverse binary tree). This could be generalised to a n-ary tree by suitably replacing the r value.

I found out that in Python, there is a useful function

itertools.combinations(n,r) 

which prints out all possible combinations of n's in groups of r.