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

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

    You can answer query of the form "Is node A a descendant of node B?" in constant time, by just using two auxiliary arrays.

    Preprocess the tree, by visiting in Depth-First order, and for each node A store its starting and ending time in the visit in the two arrays Start[] and End[].

    So, let us say that End[u] and Start[u] are respectively the ending and starting time of the visit of node u.

    Then node u is a descendant of node v if and only if:

    Start[v] <= Start[u] and End[u] <= End[v].

    and you are done, checking this condition requires just two lookup in the arrays Start and End

提交回复
热议问题