Rope data structure weights are characters in node plus weight of left subtree or both left and right subtrees?

StackOverflow https://stackoverflow.com/questions/12557003

Question

Wikipedia entry says:

Each node has a "weight" equal to the length of its string plus the sum of all the weights in its left subtree. Thus a node with two children divides the whole string into two parts: the left subtree stores the first part of the string. The right subtree stores the second part and its weight is the sum of the two parts.

I'm a bit confused, it says first that a nodes weight is the length of its string plus the sum of all the weights in its left subtree. Then it says if a node has two children (and thus a left and a right subtree), that the weight is the sum of both parts, and not just the left subtree. Looking at the diagram makes sense (the 9 directly below the 22 is a 9 and not larger because the right child/subtree of 7 does not contribute to the weight) but the phrasing seems off to me or am I misunderstanding something?

Was it helpful?

Solution

Yeah, the phrasing is off. The "weight" is the partition point, so it only includes the left substring (or the included string, if that's what you have instead).

You don't need to store the total length of a node, but modifying the rope requires that all parent nodes be notified of the change (which should be O(log n), so that's ok.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top