I am reading the following article, http://articles.sitepoint.com/article/hierarchical-data-database/2 about”Storing Hierarchical Data in a Database”.
This is talking about these structures. http://sitepointstatic.com/graphics/sitepoint_numbering.gif and http://sitepointstatic.com/graphics/table02.gif
I don’t understand the following passages. What do these mean.
“Each time you start with the children of a node, you add the right value of that node to the stack.”
and
“When you’re finished displaying a node, you remove its right value from the stack. If you count the elements in the stack, you’ll get the level of the current node.”
I am hoping someone explains these in a simpler way if possible.
To show the tree structure, children
should be indented slightly more than
their parent. We can do this by
keeping a stack of right values. Each
time you start with the children of a
node, you add the right value of that
node to the stack. You know that all
children of that node have a right
value that is less than the right
value of the parent, so by comparing
the right value of the current node
with the last right node in the stack,
you can see if you’re still displaying
the children of that parent. When
you’re finished displaying a node, you
remove its right value from the stack.
If you count the elements in the
stack, you’ll get the level of the
current node.
They’re trying to come up with a way to use Nested Sets for indenting data by the level in the tree.
So as you fetch the rows, you push the
rgtnumber onto the end of an array:This array grows as you process children and subchildren. For example, by the time we get to “Cherry” the array looks like this:
As long as we’re descending down a branch of the tree, the
rgtvalues in this should be getting less, because a child’srgtvalue is always less than its parent’srgtvalue.The next row we process is “Yellow” which has a
rgtvalue of 10. This value 10 is greater than the last value in the array, which means we’re not descending down one branch anymore, we’re on a different branch. We need to pop numbers out of the array until 10 is no longer greater than the last number in the array.Now we know that the array contains only ancestors of our current row “Yellow”.
The level in the tree is always equal to the number of elements in that array.