Skip to content
World Wide Web Server edited this page Jul 4, 2012 · 18 revisions

Category:Database

[h3]Nested Sets - Working with hierarchical data trees[/h3]

One of the most commonly used methods of representing trees of data within a database is the adjacency list model, where each record has a column dedicated to identifying the 'parent' record for this particular row of data. Using the parent identifier it becomes possible to work your way up from any node in the tree back to the uppermost parent or ancestor (also commonly referred to as the root node). In this way, you can recurse through the tree data and build up programmatically an array structure representing the tree.

However, this recursion business is somewhat expensive in terms of processor cycle consumption.

Enter then, an appropriate alternative method for handling tree data suited to situations where the tree needs to be read much more often than it needs to be changed or modified.

[strong]Nested sets, or the modified preorder inverse tree traversal[/strong]

The nested sets approach involves giving each node of the tree two integer references, one on its left hand side and the other on its right hand side. The left hand side of the root node is always '1'. The rest of the tree is numbered by travelling down the left hand side and up the right hand side of every node until you get back to the right hand side of the root node, where the number used will be exactly twice the number of nodes in the tree. Please see the reference articles for further information on this.

[h3]Nested_sets_model.php[/h3]

Clone this wiki locally