Suppose one below tree-like structure in networkx
graph:
n-----n1----n11
| |----n12
| |----n13
| |----n131
|----n2 |
| |-----n21 X
| |-----n22 |
| |----n221
|----n3
n4------n41
n5
- How to list all nodes with "subnode" and its depth, here: n,n1,n13,n2,n22,n4
- How to list all nodes without "subnode", here: n11,n12,n21,n41,n5
- How to list orphan node, here: n5 and how to list "orphan" edge, not belongs to root n edge, here n4-n41,
- How to list node with more than 2 "subnode", here n,n1
- How to deal with if n131,n221 have an edge exists in nodes traversal, will infinity loop happen?
Thanks.
Graph construction:
Using the out_degree function to find all the nodes with children:
Note that n131 and n221 also show up here since they both have an edge to each other. You could filter these out if you want.
All nodes without children:
All orphan nodes, i.e. nodes with degree 0:
To get all orphan "edges", you can get the list of components of the graph, filter out the ones that don't contain
n
and then keep only the ones that have edges:Nodes with more than 2 children:
If you traverse the tree, you will not get an infinite loop. NetworkX has traversal algorithms that are robust to this.