0

Let's say I have an array and I have to answer queries like find the sum of all elements from index i to j, now can I do this on a rooted tree, like answering such queries for path from node i to j ( On the only path that exists from i to j).

I know how to find LCA using range minimum query where we decompose it to linear array and then use a segment tree but I am not able to modify it for sum queries. How do I do that?

anker
  • 63
  • 5
  • Can you paste the code, what have you tried, so it will be easier for me to debug ur code or logic, I don't want to give you everything coded by me.... and implementing range sum queries is pretty straightforward .. – zenwraight Jul 14 '17 at 14:20
  • @zenwraight I don't have a logic right now, that's what I have asked in the question. I am asking for range sum queries on a tree not a linear array. – anker Jul 14 '17 at 14:22
  • 1
    Ohh got it, so then you might have to run a dfs or bfs on the tree and then save the values onto an array and then compute the sum range queries on it ... – zenwraight Jul 14 '17 at 14:47

1 Answers1

0

This depends on your processing requirements: do you have complexity limits, or is the goal to have working, maintainable code by lunch time?

If it's the latter, take the simple approach:

  • Locate both nodes in the tree.
  • Starting at the first node, traverse back to the root, summing the path cost as you go, maintaining the partial sum at each node.
  • Starting at the second node, also traverse-and-sum (full sum only, no partials) toward the root.
  • When you encounter a node that's an ancestor of the first one, you've found the LCA.
  • Add your current sum to the first node's partial sum for the LCA. Done.

This algorithm is easily understood by a first-term data structures student. With the consistent check for LCA, it's O(log(n)^2) -- not bad, but not the optimum of linear pre-work and constant-time query return for LCA.


If you need a faster algorithm, then I suggest that you augment the LCA pre-work algorithm so that each node also computes a hashed list (e.g. Python dictionary) of partial sums to each of its ancestors. Once you've done that, you have a constant-time computation for the LCA, and a constant-time look-up for each partial sum.

Prune
  • 76,765
  • 14
  • 60
  • 81