我在 python 中寻找一个答案来表示目录的 n 叉树。我认为文件夹的 N 叉树就是一个很好的例子。这是我的代码:
class Node(object):
def __init__(self, data):
self.data = data
self.children = []
n = Node(sys.argv[1])
def walktree(top): # recurse from "/top/"
X = [] # clear record
for f in os.listdir(top):
pathname = os.path.join(top,f)
mode = os.stat(pathname)[ST_MODE]
if S_ISDIR(mode): # It's a directory
X.append(pathname) #
walktree(pathname) # recursion
X.sort()
n.add_child(X)
我的问题是:
- 这段代码正确吗?
- 如何填充N叉树的给定节点
- 如何遍历构造的 N 叉树
1、2、3 的答案。
def dirwalk(top): # build an n_ary tree
n = Node(top) # ONE Node per folder
for f in os.listdir(top): # loop over the current dir
pathname = os.path.join(top,f) # dir + fname
mode = os.stat(pathname)[ST_MODE]
if S_ISDIR(mode): # It's a directory
ptr = dirwalk(pathname) # go down
n.add_child(ptr) # add pointer to node
return n # return Node
def traverse(n): # traverse buildt tree
for p in n: # loop over children
print p.data
traverse(p.children)