recursion - Algorithm to recursivly go through a forest of children -
Please tell me whether this is bad behavior or, in any way, a bad thing, this is in my program, I There is a need to create a method that goes through the basic element and all the child nodes of that element. My elements are like this:
| --ID | | --Part - | --Aditital information - | | 1 | 0 | Root element | | 2 | 0 | Root Amenet | | 3 | 1 | Child element 1 | | 4 | 1 | Child element 1 | | 5 | 3 | Child element 3 -------------------------------------- now If I want to get all the children of elements with ID1 (no matter if it has 1000 children or just 2 are like this example) I want to bring it to myself, but I'm not sure How is that to do this? All these elements are in a list, and this is what I am working on. Every time I am getting an element, it is necessary to see if he has any child, he is with the children. The reason for this is that I need to output the elements in the correct order. Ive probably was thinking about making it so I made a map of the layout first, and then use the map for output, but I got stuck with this idea.
Any clues? Like many of these trees, the magic word here is recursive. The order ID that you specified in the table is the order, which does not match the first depth or width first. But it's all right, the nodes have to put some data in Strucks, which will return them in the desired order. Then there is a general plan
- To find all the nodes again 'walk' tree;
- Print the given nodes
The recursive part is also easy:
-
start from the root node
-
If the root node is not in the list of nodes, then add it
- Take the first child node and do the same thing.
Something like this (pseudocode):
DFS (node, nodelist): If the node is not in the nodalast, node of each child (n, nodelist) ) Enter node in nodelist
Comments
Post a Comment