What is the difference between modified preorder and just preorder? What is the difference between modified preorder and just preorder? database database

What is the difference between modified preorder and just preorder?


I disagree slightly with the naming, and perhaps there's some confusion from your side regarding this.

I'd define "traversal" as the process of traversing.

The result we get from the traversal I'd perhaps call a "representation".

MPTT is more of a representation than a traversal.

Additionally, the value on the left can be thought of as preorder, while the value on the right can be thought of as postorder (we'll get to that...).

Thus I might have rather named it "Combined Pre-/postorder traversal representation".


Now onto what this actually is.

As mentioned above, it's merely a representation.

Let's look at an algorithm to generate this representation from a tree:

traverse(node, index)   node.left = index   for each child c of node     traverse(c, ++index)   node.right = ++index

As can be seen with the above code, we do something with the node both before and after recursing to the children, so it can be seen as some combination of pre- and postorder traversal.

Now where the more significant difference between this and pre- or postorder comes in, is how it's used.

Pre- or postorder is typically something you run on a tree or use to generate a tree from (perhaps to compactly store it to disk, while a typical pointer-based representation might be generated in memory when you actually want to use the tree).

But with MPTT, this would be how you actually represent the tree while using it. This is especially useful in databases, which aren't particularly focussed around recursion.

You'd store the MPTT values in your table, and these would allow you to efficiently perform various queries. For example: (derived from here)

  • To get all descendants of a node, you'd look for left values between the left and right values of that node.

  • To get the path to / all ancestors of a node, you'd look for nodes with left values smaller than this left value and right values greater than this right value.

Both of the above can be performed using a single query, where-as a recursive representation will require one query for each node in the path and ... a few for the descendants.