Enumerate Search Trees

In accordance with this question, the number of different search trees of a certain size is equal to the Catalan number. Can these trees be listed? That is, can someone implement the following two functions:

Node* id2tree(int id); // return root of tree

int  tree2id(Node* root); // return id of tree

(I ask because binary code for a tree (one of the answers to this question ) would be a very efficient code for representing arbitrarily large integers of an unknown range, i.e. a variable-length code for integers

0 -> 0
1 -> 100
2 -> 11000
3 -> 10100
4 -> 1110000
5 -> 1101000
6 -> 1100100
7 -> 1011000
8 -> 1010100
etc

note that the number of integers of each code length is 1, 1, 2, 5, .. (Catalan sequence). )

+3
source share
2 answers

.

:

0 -> 0 
1 -> 100 
2 -> 11000 
3 -> 10100 
4 -> 1110000 
5 -> 1101000 
6 -> 1100100 
7 -> 1011000 
8 -> 1010100 

, ( ) (, 1 0 ).

.

, n :

Left sub-tree n-1 nodes, Right sub-tree 0 nodes. (Cn-1*C0 of them)
Left sub-tree n-2 nodes, Right sub-tree 1 node.  (Cn-2*C1 of them)
Left sub-tree n-3 nodes, right sub-tree 2 nodes. (Cn-3*C2 of them)
...
...
Left sub-tree 0 nodes, Right sub-tree n-1 nodes. (C0*Cn-1 of them)

Cr = rth catalan number.

, , , : , . , . , -1 ..

, , id = S. n,

C0 + C1 + C2 +... + Cn < S <= C0 + C1 + C2 +... + Cn + 1

S n + 1 .

, P = S - (C0 + C1 + C2 +... + Cn), n + 1 .

r , Cn * C0 + Cn-1 * C1 +.. + Cn-rCr < P <= CnC0 + Cn-1 * C1 +.. + Cn-r + 1 * Cr-1

, .

P-Cn * C0 + Cn-1 * C1 +.. + Cn-r * Cr, ( ) .

, , , , , , .

, . .

+2

(-) , , ( ) node, N. ( ) -3 (, , ).

. . , , N , N . , .

, , : N , N-1 .. N , N 1. - . (, ).

, , , , ( ) . , N, 1 N, , .

, .

0

Source: https://habr.com/ru/post/1718636/


All Articles