简体   繁体   English

如何在Networkx中手动实施DFS

[英]How to implement DFS by hand in networkx

I would like to implement by hand a simple DFS preorder traversal of a tree in networkx . 我想在networkx中手动实现对树的简单DFS预先遍历。 As a toy example, here is a simple tree: 作为一个玩具示例,这是一棵简单的树:

import matplotlib.pyplot as plt
import networkx as nx
T = nx.generators.balanced_tree(2, 3)
nx.draw_networkx(T)
plt.show()

在此处输入图片说明

As this is a binary tree, I should in principle be able to perform a preorder traversal with something like: 由于这是一个二叉树,因此原则上我应该能够执行类似以下内容的预遍历:

def preOrder(root):
    if root:
        print(root.data)
        preOrder(root.left)
        preOrder(root.right)

However, I can't see how to do this in networkx. 但是,我看不到如何在networkx中执行此操作。 How do I find the root and what is the networkx version of node.left and node.right? 如何找到根以及node.left和node.right的networkx版本是什么?


Update 1 更新1

In networkx there is list(nx.dfs_preorder_nodes(T, source=r, depth_limit=1)) which treats the tree as an undirected graph and finds all the children from r which it treats as the root. 在networkx中,存在list(nx.dfs_preorder_nodes(T, source=r, depth_limit=1)) ,该树将树视为无向图,并从r中将其视为根的所有子级找到。 I don't see how to use this, for example, to mimic node.left and node.right to perform the preorder traversal. 我看不到如何使用它来模仿node.left和node.right来执行预遍历。 It will for example give [0,3,4] if r = 1 . 例如,如果r = 1 ,它将给出[0,3,4]

Networkx allows you varied ways to traverse nodes of a graph. Networkx允许您使用多种方式遍历图的节点。 In your case you could use dfs_preorder_nodes and limit depth to 1 : 在您的情况下,您可以使用dfs_preorder_nodes并将深度限制为1

>>> G = nx.path_graph(5)
>>> list(nx.dfs_preorder_nodes(G, source=0))
[0, 1, 2, 3, 4]
>>> list(nx.dfs_preorder_nodes(G, source=0, depth_limit=1))
[0, 1]

Note the API: 注意API:

If a source is not specified then a source is chosen arbitrarily and repeatedly until all components in the graph are searched. 如果未指定来源,则将任意重复选择来源,直到搜索图中的所有组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM