A problem for seniors is to ask for n different nodes to form all two-fork trees, regardless of rotational symmetry and isomorphism.
Problem Description: Given n nodes, see how many different two-fork trees can be formed and output
Algorithm Description: Using the most basic "divide and Conquer" (Divide and Conquer) thought, select a node as the root node, the remaining nodes composed of a collection of Split (Partition), part of the left subtree to recursive, and the other part of the right subtree recursion. The focus is on two parts: part using binary to split the set, in fact, is the set of the "power set", the other part is how to store. You can also search for violence.
Test case: n=3, capable of forming 30 different binary trees.
Code:
1#include <iostream>2#include <string>3#include <vector>4 using namespacestd;5 6vector<string> Generate_tree (Constvector<string> &nodes) {7 if(Nodes.empty ()) {8 returnvector<string>{"*"};9}Else if(1==nodes.size ()) {Ten returnvector<string>{nodes[0]}; One } Avector<string>trees, TMP, left, right, L_tree, R_tree; - for(size_t i =0; I < nodes.size (); ++i) { -TMP =nodes; theTmp.erase (Tmp.begin () +i); - for(size_t j =0; J <1<<tmp.size (); ++J) {//Do set partition - left.clear (); - right.clear (); + for(size_t k =0; K < Tmp.size (); ++k) { - if(! (J & (1<<k )) { + Left.push_back (Tmp[k]); A}Else { at Right.push_back (Tmp[k]); - } - } -L_tree =Generate_tree (left); -R_tree =Generate_tree (right); - for(Const string&L:l_tree) { in for(Const string&R:r_tree) { -Trees.push_back (Nodes[i] +"("+ L +","+ R +")"); to } + } - } the } * returntrees; $ }Panax Notoginseng - intMain () { thevector<string> nodes{"A","B","C"}; +vector<string> trees =Generate_tree (nodes); Acout << trees.size () <<Endl; the for(Auto &i:trees) { +cout << i <<Endl; - } $ return 0; $}
Because of the use of the C++11 feature, the file's compile command is
g++-std=c++11 generate_tree.cc
The output result is
30A (b (c,*), *) A (b (*,c), *) A (c (b,*), *) A (c (*,b), *) A (c,b) a (b,c) a (*,b (c,*)) A (*,b)) A (*,c (*,c)) A (A ()) B (b,* (*,C)) , *) B (A (*,c), *) b (c (a,*), *) b (c (*,a), *) b (c,a) b (a,c) b (*,a (c,*)) b (*,a (*,c)) b (*,c (a,*)) b (*,c (*,a)) C (A (b,*), *) C (A (*,B) ), *) C (b (a,*), *) C (b (*,a), *) C (b,a) C (b) C (*,a (b,*)) C (*,a (*,B)) C (*,b (a,*)) C (*,b (*,a))
When n=4, there are 336 kinds of
When n=5, there are 5040 kinds of
Traverse all two-fork trees that can be formed by n nodes