O(1) algorithm to determine if node is descendant of another node in a multiway tree?

后端 未结 7 1302
情书的邮戳
情书的邮戳 2021-02-08 04:37

Imagine the following tree:

    A
   / \\
  B   C
 / \\   \\
D   E   F

I\'m looking for a way to query if for example F is a descendant of A (n

7条回答
  •  一生所求
    2021-02-08 04:44

    I don't know if this would fit your problem, but one way to store hierarchies in databases, with quick "give me everything from this node and downwards" features is to store a "path".

    For instance, for a tree that looks like this:

        +-- b
        |
    a --+       +-- d
        |       |
        +-- c --+
                |
                +-- e
    

    you would store the rows as follows, assuming the letter in the above tree is the "id" of each row:

    id    path
    a     a
    b     a*b
    c     a*c
    d     a*c*d
    e     a*c*e
    

    To find all descendants of a particular node, you would do a "STARTSWITH" query on the path column, ie. all nodes with a path that starts with a*c*

    To find out if a particular node is a descendant of another node, you would see if the longest path started with the shortest path.

    So for instance:

    • e is a descendant of a since a*c*e starts with a
    • d is a descendant of c since a*c*d starts with a*c

    Would that be useful in your instance?

提交回复
热议问题