Lably
Skip to content

Level ancestor problem

  • 5 min read
  • 3 chapters

Related on Lably

Through Preprocessor, Data structure and Recursion

More precisely, let T be a rooted tree with n nodes, and let v be an arbitrary node of T. The level ancestor query LA(v,d) requests the ancestor of node v at depth d, where the depth of a node v in a tree is the number of edges on the shortest path from the root of the tree to node v. It is possible to solve this problem in constant time per query, after a preprocessing algorithm that takes O(n) and that builds a data structure that uses O(n) storage space.

Jump pointer algorithm

The jump pointer algorithm pre-processes a tree in O(n log n) time and answers level ancestor queries in O(log n) time. The jump pointer algorithm associates up to log n pointers to each vertex of the tree. These pointers are called jump pointers because they jump up the tree towards the root of the tree. For a given node v of a tree, the algorithm stores an array of length l jumpers where ℓ=⌊log2⁡(depth⁡(v))⌋. The ith element of this array points to the 2ith ancestor of v. Using such data structure helps us jump halfway up the tree from any given node. When the algorithm is asked to process a query, we repeatedly jump up the tree using these pointers. The number of jumps will be at most log n and therefore queries can be answered in log n time.

Sign in to keep reading

2 more chapters are free with a Lably account.

More in Computing and communication