Iterate over top two levels of Treeview nodes?
-
Have a Treeview with 3 levels, is there a simple way to iterate in a single loop over the top two levels:
- Node 1
-> Node 2
--> Node 3 - Node 4
- Node 5
-> Node 6
--> Node 7
Need to loop over Nodes: 1, 2, 4, 5, 6
- Node 1
-
for node0 in topLevelNodes: doSomething(node0) for node1 in node0.children: doSomething(node1)
-
@JonB That's what I'm doing currently. Was hoping there was a better way to get nodes of n-levels as a singular list and iterate over them.
@Taytoo said in Iterate over top two levels of Treeview nodes?:
@JonB That's what I'm doing currently. Was hoping there was a better way to get nodes of n-levels as a singular list and iterate over them.
It is possible by using a different representation of the tree. It is not immediately straightforward though. Typically trees can be 'linearized' by keeping a left:right traversal index (the so-called "nested set model").
-
@JonB That's what I'm doing currently. Was hoping there was a better way to get nodes of n-levels as a singular list and iterate over them.
@Taytoo said in Iterate over top two levels of Treeview nodes?:
Was hoping there was a better way to get nodes of n-levels as a singular list and iterate over them.
There is, but that is not what you asked for. You wrote:
is there a simple way to iterate in a single loop over the top two levels
My answer would not scale for n-levels. Nor would it be right for "visit every node which is not a leaf". One would probably do either of those recursively. And it would not be a "single loop", which I now notice but did not before, if that is what is vital to you. So you have to state exactly what it is you are looking for.