def get_relation(node,pre_level,f,t = None,level = None):
'''
存为树结构
node:当前结点的上一个结节点
pre_level:上一节点的等级
f:读取数据的迭代器
t:一条数据
level:当前节点的等级
'''
node_cur = node_info()
while True:
if not t:
t = f.readline()
#通过\t来确定层级关系
t = t.replace('\n','').split('\t')
level = len(t)
if level == pre_level+1:
node_cur.value = t[-1]
node_cur.level = level
node_cur.pre = node
node.nexts.append(node_cur)
return get_relation(node_cur,node_cur.level,f)
else:
if not node.pre.value:
return node
return get_relation(node.pre,node.pre.level,f,t,level)
广度优先
def bfs(node):
'''
广度优先
'''
if node is None:
return
result = []
que = Queue()
que.put(node)
while not que.empty():
cur = que.get()
result.append(cur.value)
for j in cur.nexts:
que.put(j)
return result
深度优先
def dfs(node):
'''
深度优先
'''
if node is None:
return
result = []
#检查节点是否输入过
nodeSet = set()
stack = []
result.append(node.value)
nodeSet.add(node)
stack.append(node)
while len(stack) > 0:
cur = stack.pop()
for next in cur.nexts:
if next not in nodeSet:
stack.append(cur)
stack.append(next)
nodeSet.add(next)
result.append(next.value)
break
return result
调用
if __name__ == '__main__':
f = open('概念', 'r', encoding='utf-8')
res = node_info()
root = get_relation(res,0,f)
f.close()
bfs_result = bfs(root)
dfs_result = dfs(root)
# print(bfs_result)
# print(dfs_result)