用栈和队列模拟目录的深度遍历和广度遍历

tech2022-08-08  128

1.深度遍历

python中没有栈的数据结构我们使用列表模仿栈的工作原理

使用列表的append方法模拟压栈,使用pop方法模拟出栈 

import os

 

def deapLook(path):

stack = []

stack.append(path)

 

#当栈为空结束循环

while len(stack) != 0:

#从栈里取数

dirPath = stack.pop()

 

fileList = os.listdir(dirPath)

 

#遍历目录下所有文件

for fileName in fileList:

fileAbspath = os.path.join(dirPath, fileName)

if os.path.isdir(fileAbspath):

print("目录", fileName)

#是目录就压栈

stack.append(fileAbspath)

else:

print("普通文件", fileName)

 

deapLook(r"D:\dir")

2.广度遍历

使用队列来模拟广度遍历

import os

import collections

 

def getAlldir(path):

queue = collections.deque()

#进队列

queue.append(path)

 

while len(queue) != 0:

#出队

pathDir = queue.popleft()

 

fileList = os.listdir(pathDir)

#遍历当前路径

for fileName in fileList:

#绝对路径

fileAbsPath = os.path.join(pathDir, fileName)

if os.path.isdir(fileAbsPath):

#如果是目录,进队列

print("目录:%s" % (fileName))

queue.append(fileAbsPath)

else:

print("普通文件:%s" % (fileName))

 

getAlldir(r"D:\dir")

最新回复(0)