0

The problem is: Given this kind of forest:

enter image description here if we have a node, how can we get the descendants of it?

I thought this algorithm that I think is pretty efficient when talking about reading all descendants adding some little overhead in the writing(it's not too much):

Firstly, to simplify, let's suppose that the number of root nodes is limited to N. We then will need to store a list with the N first primes. When we create the first node we will assign the 2nd prime of our list (3) to a field name treeId, the second root node gets the 3rd prime, and so on (we can keep a counter of how many roots there are).

To create a child of a parent, we will take the parent's treeId and recursively multiply to the parent of parent treeId and then multiply by 2 (the first prime). To know all descendent of a node with nodeId = k, we can do a linear search and get all nodes whose treeId is different than k and is divisible by k.

We can remove the limit of N records as root creating another index treeGroupId so that a child will inherit the same treeGroupId of the parent and we verify if two nodes have the same treeGroupId to then apply the first verification algorithm.

My question is: Is this a known technique to search for Tree decendents? Is there any flow in this algorithm. If there's can we have better result?

trincot
  • 317,000
  • 35
  • 244
  • 286
  • 2
    *"Given a node from a tree [...] let's suppose that the number of root nodes is limited to N."*: if it is a tree, then what do you mean with *multiple* roots? A rooted tree only has **one** root. Secondly, I don't understand the problem. In which data structure is the tree defined? For example, if it is an adjacency list, you can find all descendants by traversing that data structure. – trincot Jun 12 '22 at 10:47
  • My tree knowledge is not great, but I think that I meant a multi-tree or a tree that can have multiples root. I don't know if multitree it's the right definition, if it's please someone confirms me for me to edit the post. –  Jun 12 '22 at 16:03
  • 2
    Maybe you mean a *forest*, i.e. a collection of trees. Could you edit your question and describe how this graph is represented in a data structure? – trincot Jun 12 '22 at 16:05
  • I'm sorry I didn't draw it right, a node shouldn't be able to have two parents. I will correct that. –  Jun 15 '22 at 01:11
  • 1
    OK; that is a forest. – trincot Jun 15 '22 at 05:04

1 Answers1

0

In the context of prime factorization, one known solution strategy is to use a so-called factor tree.