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

后端 未结 7 1301
情书的邮戳
情书的邮戳 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:47

    For a M-way tree, instead of your bit array, why not just store the binary "trie id" (using M bits per level) with each node? For your example (assuming M==2) : A=0b01, B=0b0101, C=0b1001, ...

    Then you can do the test in O(1):

    bool IsParent(node* child, node* parent)
    { 
       return ((child->id & parent->id) == parent->id)
    }
    

    You could compress the storage to ceil(lg2(M)) bits per level if you have a fast FindMSB() function which returns the position of the most significant bit set:

    mask = (1<<( FindMSB(parent->id)+1) ) -1;
    retunr (child->id&mask == parent->id);
    

提交回复
热议问题