# Storing Hierarchical Data in a Database, Part 2

## Modified Preorder Tree Traversal

Now, letâ€™s have a look at another method for storing trees. Recursion can be slow, so we would rather not use a recursive function. Weâ€™d also like to minimize the number of database queries. Preferably, weâ€™d have just one query for each activity.

Weâ€™ll start by laying out our tree in a horizontal way. Start at the root node (â€˜Foodâ€™), and write a 1 to its left. Follow the tree to â€˜Fruitâ€™ and write a 2 next to it. In this way, you walk (traverse) along the edges of the tree while writing a number on the left and right side of each node. The last number is written at the right side of the â€˜Foodâ€™ node. In this image, you can see the whole numbered tree, and a few arrows to indicate the numbering order.

Weâ€™ll call these numbers left and right (e.g. the left value of â€˜Foodâ€™ is 1, the right value is 18). As you can see, these numbers indicate the relationship between each node. Because â€˜Redâ€™ has the numbers 3 and 6, it is a descendant of the 1-18 â€˜Foodâ€™ node. In the same way, we can say that all nodes with left values greater than 2 and right values less than 11, are descendants of 2-11 â€˜Fruitâ€™. The tree structure is now stored in the left and right values. This method of walking around the tree and counting nodes is called the â€˜modified preorder tree traversalâ€™ algorithm.

Before we continue, letâ€™s see how these values look in our table:

Note that the words â€˜leftâ€™ and â€˜rightâ€™ have a special meaning in SQL. Therefore, weâ€™ll have to use â€˜lftâ€™ and â€˜rgtâ€™ to identify the columns. Also note that we donâ€™t really need the â€˜parentâ€™ column anymore. We now have the lft and rgt values to store the tree structure.

*Retrieve the Tree*

If you want to display the tree using a table with left and right values, youâ€™ll first have to identify the nodes that you want to retrieve. For example, if you want the â€˜Fruitâ€™ subtree, youâ€™ll have to select only the nodes with a left value between 2 and 11. In SQL, that would be:

`SELECT * FROM tree WHERE lft BETWEEN 2 AND 11;`

That returns:

Well, there it is: a whole tree in one query. To display this tree like we did our recursive function, weâ€™ll have to add an ORDER BY clause to this query. If you add and delete rows from your table, your table probably wonâ€™t be in the right order. We should therefore order the rows by their left value.

`SELECT * FROM tree WHERE lft BETWEEN 2 AND 11 ORDER BY lft ASC;`

The only problem left is the indentation.

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.

`<?php Â `

function display_tree($root) { Â

Â Â // retrieve the left and right value of the $root node Â

Â Â $result = mysql_query('SELECT lft, rgt FROM tree '. Â

Â Â Â Â Â Â Â Â Â Â Â Â Â 'WHERE title="'.$root.'";'); Â

Â Â $row = mysql_fetch_array($result); Â

Â

Â Â // start with an empty $right stack Â

Â Â $right = array(); Â

Â

Â Â // now, retrieve all descendants of the $root node Â

Â Â $result = mysql_query('SELECT title, lft, rgt FROM tree '. Â

Â Â Â Â Â Â Â Â Â Â Â Â Â 'WHERE lft BETWEEN '.$row['lft'].' AND '. Â

Â Â Â Â Â Â Â Â Â Â Â Â Â $row['rgt'].' ORDER BY lft ASC;'); Â

Â

Â Â // display each row Â

Â Â while ($row = mysql_fetch_array($result)) { Â

Â Â Â Â // only check stack if there is one Â

Â Â Â Â if (count($right)>0) { Â

Â Â Â Â Â Â // check if we should remove a node from the stack Â

Â Â Â Â Â Â while ($right[count($right)-1]<$row['rgt']) { Â

Â Â Â Â Â Â Â Â array_pop($right); Â

Â Â Â Â Â Â } Â

Â Â Â Â } Â

Â

Â Â Â Â // display indented node title Â

Â Â Â Â echo str_repeat(' Â ',count($right)).$row['title']."n"; Â

Â

Â Â Â Â // add this node to the stack Â

Â Â Â Â $right[] = $row['rgt']; Â

Â Â } Â

} Â

?>

If you run this code, youâ€™ll get exactly the same tree as with the recursive function discussed above. Our new function will probably be faster: it isnâ€™t recursive and it only uses two queries.

*The Path to a Node*

With this new algorithm, weâ€™ll also have to find a new way to get the path to a specific node. To get this path, weâ€™ll need a list of all ancestors of that node.

With our new table structure, that really isnâ€™t much work. When you look at, for example, the 4-5 â€˜Cherryâ€™ node, youâ€™ll see that the left values of all ancestors are less than 4, while all right values are greater than 5. To get all ancestors, we can use this query:

`SELECT title FROM tree WHERE lft < 4 AND rgt > 5 ORDER BY lft ASC;`

Note that, just like in our previous query, we have to use an ORDER BY clause to sort the nodes. This query will return:

`+-------+`

| title |

+-------+

| Food |

| Fruit |

| Red |

+-------+

We now only have to join the rows to get the path to â€˜Cherryâ€™.

*How Many Descendants*

If you give me the left and right values of a node, I can tell you how many descendants it has by using a little math.

As each descendant increments the right value of the node with 2, the number of descendants can be calculated with:

`descendants = (right Ã¢â‚¬â€œ left - 1) / 2`

With this simple formula, I can tell you that the 2-11 â€˜Fruitâ€™ node has 4 descendant nodes and that the 8-9 â€˜Bananaâ€™ node is just a child, not a parent.