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

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

    Are your input trees always static? If so, then you can use a Lowest Common Ancestor algorithm to answer the is descendant question in O(1) time with an O(n) time/space construction. An LCA query is given two nodes and asked which is the lowest node in the tree whose subtree contains both nodes. Then you can answer the IsDescendent query with a single LCA query, if LCA(A, B) == A or LCA(A, B) == B, then one is the descendent of the other.

    This Topcoder algorithm tuorial gives a thorough discussion of the problem and a few solutions at various levels of code complexity/efficiency.

提交回复
热议问题