List & Tree convert to each other:
The algorithm that converts a flat list into a tree structure is commonly known as the “List to Tree” algorithm or “Array to Tree” algorithm. It takes a list or array of items, where each item has an identifier and a parent identifier, and transforms it into a hierarchical tree structure.
The algorithm typically involves iterating over the list and creating tree nodes for each item. It maintains a mapping between the item’s identifier and the corresponding tree node to efficiently locate and connect the nodes. By using the parent identifier, the algorithm determines the parent node for each item and adds the item’s node to the parent’s list of children nodes. Finally, the algorithm identifies the root node(s) by finding the node(s) with a specific parent identifier(eg., 0 or null).
The implementation of the algorithm may vary based on the programming language and specific requirements. However, the core idea remains the same: iteratively process the list, create tree nodes, establish parent-child relationships, and identify the root node(s) to form a tree structure.
📝 Critical process
Iteratively process the list or array
Create tree nodes based on elements in the list
Maintain the relationship between parent and child by creating a map
Determine the root node based on specific conditions, such as parentId = 0 or null
Pseudo-code
The anatomy of knowledge points
typescript creates datatypes for list elements and tree nodes like this: