Check if 2 tree nodes are related (ancestor/descendant) in O(1) with pre-processing

前端 未结 3 1135
北恋
北恋 2020-12-28 09:48

Check if 2 tree nodes are related (i.e. ancestor-descendant)

  • solve it in O(1) time, with O(N) space (N = # of nodes)
  • pre-processing is allowed
3条回答
  •  一整个雨季
    2020-12-28 10:19

    You can do it in O(n) preprocessing time, and O(n) space, with O(1) query time, if you store the preorder number and postorder number for each vertex and use this fact:

    For two given nodes x and y of a tree T, x is an ancestor of y if and only if x occurs before y in the preorder traversal of T and after y in the post-order traversal.

    (From this page: http://www.cs.arizona.edu/xiss/numbering.htm)

    What you did in the worst case is Theta(d) where d is the depth of the higher node, and so is not O(1). Space is also not O(n).

提交回复
热议问题