I've developed a recursive algorithm in c++ to select a random node inside a Tree (not necessarily binary). This is the code:
Tree* Tree::SelectRandomNode()
{
static int n = 0;
static int selected;
Tree *Ret;
n++;
// If It is a Terminal Node, it chooses a random node between those we got through
if( !InnerNode ) selected = rand()%n;
// Else if it is an Inner Node, it keeps going through random children
else Ret = Child[ rand()%NumberOfChildren ]->SelectRandomNode();
n--;
//Then, when we get back, we take the pointer of the selected node
if( n == selected ) return this;
else return ret;
}
What do you think about it? Is it efficient? Then, for curiosity, is this an O(log(n)) algorithm? There are faster ways to achieve this?
PS: I know very little about computational complexity.
Aucun commentaire:
Enregistrer un commentaire