Unlimited classification algorithm for left and right values

Source: Internet
Author: User
: This article mainly introduces the implementation algorithm of left and right values of infinite classification. if you are interested in the PHP Tutorial, please refer to it. I. INTRODUCTION

In terms of product classification, multi-level tree structure forums, mail lists, and many other places, we all encounter the following problem: how to store multi-level structured data? In PHP applications, relational databases are usually used to store background data. they can store a large amount of data and provide efficient data retrieval and update services. However, the basic form of relational data is an interactive table, which is a flat structure. if you want to store a multi-level tree structure in a relational database, you need to perform reasonable translation work. Next, I will discuss what I have seen and some practical experiences with you:
There are basically two common design methods for storing hierarchical data in a flat database:
* Adjacency list model)
* Modified preorder tree traversal algorithm)

II. model

Here I use a simple food directory as our sample data.
The data structure is as follows:

Food||---Fruit|    ||    |---Red|    |    ||    |    |--Cherry|    ||    +---Yellow|          ||          +--Banana|+---Meat      |--Beef      +--Pork

To take care of PHP fans who are confused about English

Food: Fruit Red: Red Cherry: Cherry Yellow: Yellow Banana: Banana Meat: Meat Beef: Beef Pork: Pork

III. implementation

1. adjacency list model)

This mode is often used and has been introduced in many tutorials and books. We add a property parent to each node to represent the parent node of the node and describe the entire tree structure through a flat table. According to this principle, the data in the example can be converted into the following table:
The following code is used:

+-----------------------+|   parent |    name    |+-----------------------+|          |    Food    ||   Food   |   Fruit    ||   Fruit  |    Green   ||   Green  |    Pear    ||   Fruit  |    Red     ||   Red    |    Cherry  ||   Fruit  |    Yellow  ||   Yellow |    Banana  ||   Food   |    Meat    ||   Meat   |    Beef    ||   Meat   |    Pork    |+-----------------------+

We can see that Pear is a child node of Green and Green is a child node of Fruit. The root node 'food' has no parent node. To briefly describe this problem, the name is used in this example to represent a record. In the actual database, you need to use the numerical id to mark each node. the table structure of the database should be like this: id, parent_id, name, descr partition ption.
With such a table, we can store the entire multi-level tree structure through the database.

Show multi-level tree. if we need to display such a multi-level structure, we needRecursive functions.
The following code is used:


  

Use this function for the root node (Food) of the entire structure to print the entire multi-level tree structure. because Food is the root node, its parent node is empty, so we call it like this: display_children (", 0 ). The contents of the entire tree are displayed:

Food    Fruit        Red            Cherry        Yellow            Banana    Meat        Beef        Pork

If you only want to display a part of the entire structure, such as the Fruit part, you can call display_children ('fruit', 0 );

Using the same method, we can know the path from the root node to any node. For example, the path of Cherry is "Food>; Fruit>; Red ". To get such a path, we need to start from the deepest level of "Cherry" and query to get its parent node "Red" to add it to the path, then we query the Red parent node and add it to the path, and so on until the "Food" at the highest level. the following code is used:


  

If you use this function for "Cherry": print_r (get_path ('cherry'), you will get an array like this:

Array (    [0] => Food    [1] => Fruit    [2] => Red)

How to print it into the desired format is yours.

Disadvantages:
This method is simple, easy to understand, and easy to use. But there are also some shortcomings. It is mainly because the running speed is very slow. because each node needs to query the database, when the data volume is large, many queries are required to complete a tree. In addition, due to recursive operations, each level of recursion consumes some memory, so the space utilization efficiency is relatively low.

2. pre-sorted traversal tree algorithm

Now let's take a look at another method that does not use recursive computing and is faster. this is the pre-sorted traversal tree (modified preorder tree traversal algorithm)
This method is rarely used and is not easy to understand for the first time. However, because this method does not use recursive query algorithms, it has higher query efficiency.

First, we will draw the multilevel data on the paper in the following way, write 1 on the left side of the root node Food, and then write 2 down the tree to the left side of the Fruit, and then proceed, along the edge of the entire tree, each node is marked with numbers on the left and right. The last digit is 18 on the right of the Food. In the figure below, you can see the multilevel structure of the entire labeled number. (Not understood? Point your finger at the number from 1 to 18 to see what's going on. I still don't understand. I'll try again. pay attention to moving your finger ).
These numbers indicate the relationship between each node. The Red number is 3 and 6, and it is the child node of "Food" 1-18. Similarly, we can see that all nodes with a left value greater than 2 and a right value less than 11 are child nodes with "Fruit" 2-11.
The following code is used:

1 Food 18|            +------------------------------+            |                              |2 Fruit 1112 Meat 17|                              |    +-------------+                 +------------+    |             |                 |            |3 Red 67 Yellow 1013 Beef 1415 Pork 16|             |4 Cherry 58 Banana 9

In this way, the entire tree structure can be stored in the database through left and right values. Before proceeding, let's take a look at the data tables that have been organized below.
The following code is used:

+----------+------------+-----+-----+|  parent  |    name    | lft | rgt |+----------+------------+-----+-----+|          |    Food    | 1   | 18  ||   Food   |   Fruit    | 2   | 11  ||   Fruit  |    Red     | 3   |  6  ||   Red    |    Cherry  | 4   |  5  ||   Fruit  |    Yellow  | 7   | 10  ||   Yellow |    Banana  | 8   |  9  ||   Food   |    Meat    | 12  | 17  ||   Meat   |    Beef    | 13  | 14  ||   Meat   |    Pork    | 15  | 16  |+----------+------------+-----+-----+

Note: Since "left" and "right" have special meanings in SQL, we need to use "lft" and "rgt" to represent left and right fields. In addition, the "parent" field is no longer required to represent the tree structure. That is to say, the following table structure is enough.
The following code is used:

+------------+-----+-----+|    name    | lft | rgt |+------------+-----+-----+|    Food    | 1   | 18  ||    Fruit   | 2   | 11  ||    Red     | 3   |  6  ||    Cherry  | 4   |  5  ||    Yellow  | 7   | 10  ||    Banana  | 8   |  9  ||    Meat    | 12  | 17  ||    Beef    | 13  | 14  ||    Pork    | 15  | 16  |+------------+-----+-----+

Now we can get data from the database. for example, if we need to get all the nodes under the "Fruit" item, we can write the query statement as follows:

SELECT * FROM tree WHERE lft BETWEEN 2AND11;

The query returns the following results.
The following code is used:

+------------+-----+-----+|    name    | lft | rgt |+------------+-----+-----+|    Fruit   | 2   | 11  ||    Red     | 3   |  6  ||    Cherry  | 4   |  5  ||    Yellow  | 7   | 10  ||    Banana  | 8   |  9  |+------------+-----+-----+

As you can see, all these nodes can be obtained through a single query. To be ableRecursive functionsIn this way, the entire tree structure is displayed. we also need to sort such queries. Sort by the left value of the node:

SELECT * FROM tree WHERE lft BETWEEN 2AND11ORDERBY lft ASC;

The remaining questions show how to indent the hierarchy.
The following code is used:


  0) {// check whether the node should be removed from the stack while ($ right [count ($ right)-1] <$ row ['rgt ']) {array_pop ($ right) ;}// indent the node name echo str_repeat ('', count ($ right )). $ row ['name']. "\ n"; // add this node to the stack $ right [] = $ row ['rgt '] ;}}?>

If you run the above functions, you will getRecursive functionsSame result. But our new function may be faster, because there are only two database queries.
It is easier to know the path of a node. if we want to know the path of Cherry, we will use its left and right values 4 and 5 for a query.

SELECT name FROM tree WHERE lft < 4AND rgt >; 5ORDERBY lft ASC;

The following result is displayed:
The following code is used:

+------------+|    name    |+------------+|    Food    ||    Fruit   ||    Red     |+------------+

How many child nodes does a node have? Very simple, descendant total = (right-left-1)/2

descendants = (right – left - 1) / 2

Don't believe it? Calculate it by yourself.
With this simple formula, we can quickly calculate that the "Fruit 2-11" node has four child nodes, while the "Banana 8-9" node has no child nodes, that is, it is not a parent node.
Amazing, right? Although I have used this method many times, it is amazing every time I do this.
This is indeed a good method, but is there any way to help us establish such a data table with left and right values? Here we will introduce a function that can automatically convert a table with the name and parent structure into a data table with the left and right values.
The following code is used:


  

Of course, this function isRecursive functionsWe need to run this function from the root node to reconstruct a tree with left and right values.

rebuild_tree('Food',1);

This function looks a little complicated, but its function is the same as the number of a table manually. it is to convert a three-dimensional multi-layer structure into a data table with left and right values.

How can we add, update, and delete a node for such a structure?
There are two methods to add a node:
First, retain the original name and parent structure, and add data to the data in the old method. after each added piece of data, use the rebuild_tree function to re-number the entire structure.
Second, the more efficient way is to change all the values on the right of the new node. For example, we want to add a new fruit "Strawberry" (Strawberry) which will become the last child node of the "Red" node. First, we need to make some space for it ." The right value of Red should be changed from 6 to 8, and the left and right values of Yellow 7-10 should be changed to 9-12. And so on, we can know that if we want to free up space for the new value, we need to add 2 to all the nodes with the left and right values greater than 5 (5 is the right value of the last sub-node of "Red. So we perform database operations like this:

UPDATE tree SET rgt = rgt + 2WHERE rgt > 5;UPDATE tree SET lft = lft + 2WHERE lft > 5;

In this way, we can create a new data node in the new inserted value. its left and right values are 6 and 7 respectively.

INSERTINTO tree SET lft=6, rgt=7, name='Strawberry';

Make another query! How is it? Soon.

IV. Conclusion

Now, you can use two different methods to design your multi-level database structure. it depends on your personal judgment, however, I prefer the second method for a structure with a large number of layers. If you want to query a small amount of data that requires frequent addition and updates, the first method is simpler.
In addition, you can write the rebuild_tree () and space-free operations into the database end if the database supportsTriggerThe function is automatically executed during insertion and update, which improves the running efficiency and makes it easier to add SQL statements for new nodes.

Http://www.cnblogs.com/guowei1027/archive/2009/12/14/1623507.html

The above introduces the implementation algorithm of the left and right values of infinite classification, including some content, and hope to be helpful to friends who are interested in PHP tutorials.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.