How to realize the Tree structure Generation algorithm of Infinite level Classification by Python
This article is to share with you about Python how to achieve infinite classification tree structure generation algorithm, the editor thinks it is very practical, so share it with you to learn, I hope you can get something after reading this article, say no more, follow the editor to have a look.
There are many application scenarios of infinite-level classification tree structure. For example, the back-end R & D needs to read out the relevant permissions of the user and generate the tree structure. After getting the permission tree, the front-end R & D can display the columns that the user has permission to access according to the structure; for example, the columns on the web page are graded:
The author also scratched his head when he first came into contact with the requirements of tree structure generation, and later found a generation algorithm with less code and clear and easy to understand: recursion.
First, make sure that the category information stored in the database is as follows:
[{"id": 1, "name": 'appliance', "parent": 0}, {"id": 2, "name": 'fruit', "parent": 0}, {"id": 3, "name": 'household appliances', "parent": 1}, {"id": 4, "name": 'hairdryer', "parent": 3}, {"id": 5, "name": 'fan' "parent": 3}, {"id": 6, "name": 'desk lamp', "parent": 3}, {"id": 7, "name": 'commercial electrical appliances', "parent": 1}, {"id": 8, "name": 'large electric cooker', "parent": 7},]
The field parent records the parent number of this entry, for example, the parent number of the hair dryer is 3, that is, the hair dryer belongs to household appliances, and the parent number of household appliances is 1, that is, household appliances belong to electrical appliances. The hair dryer entry is not directly associated with the electrical item, but the electrical appliance needs to be indicated by a tree structure.