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

后端 未结 7 1298
情书的邮戳
情书的邮戳 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 05:03

    In a pre-order traversal, every set of descendants is contiguous. For your example,

    A B D E C F
    +---------+ A
      +---+ B
        + D
          + E
            +-+ C
              + F
    

    If you can preprocess, then all you need to do is number each node and compute the descendant interval.

    If you can't preprocess, then a link/cut tree offers O(log n) performance for both updates and queries.

    0 讨论(0)
提交回复
热议问题