我有一个缩进的文本文件,将用于构建一棵树。每行代表一个节点,缩进表示深度以及当前节点是其父节点的子节点。
例如,文件可能如下所示:
ROOT Node1 Node2 Node3 Node4 Node5 Node6
这说明ROOT包含三个子节点:1、5和6,Node1有一个子节点:2,Node2有一个子节点:3,等等。
我已经想出了一种递归算法,并且已经编写并且可以工作,但它很丑陋,特别是对上述示例的处理很粗略(当从节点4到节点5时)。
它使用“缩进计数”作为递归的基础,因此如果缩进数=当前深度+1,则我会深入一层。但这意味着当我读取一个缩进较少的行时,我必须一次回退一级,每次检查深度。
以下是我的代码:
例如,文件可能如下所示:
ROOT Node1 Node2 Node3 Node4 Node5 Node6
这说明ROOT包含三个子节点:1、5和6,Node1有一个子节点:2,Node2有一个子节点:3,等等。
我已经想出了一种递归算法,并且已经编写并且可以工作,但它很丑陋,特别是对上述示例的处理很粗略(当从节点4到节点5时)。
它使用“缩进计数”作为递归的基础,因此如果缩进数=当前深度+1,则我会深入一层。但这意味着当我读取一个缩进较少的行时,我必须一次回退一级,每次检查深度。
以下是我的代码:
def _recurse_tree(node, parent, depth):
tabs = 0
while node:
tabs = node.count("\t")
if tabs == depth:
print "%s: %s" %(parent.strip(), node.strip())
elif tabs == depth + 1:
node = _recurse_tree(node, prev, depth+1)
tabs = node.count("\t")
#check if we have to surface some more
if tabs == depth:
print "%s: %s" %(parent.strip(), node.strip())
else:
return node
else:
return node
prev = node
node = inFile.readline().rstrip()
inFile = open("test.txt")
root = inFile.readline().rstrip()
node = inFile.readline().rstrip()
_recurse_tree(node, root, 1)
目前我只是打印节点来验证每行的父节点是否正确,但也许有更简洁的方法吗?特别是在elif块中,当我从每次递归调用返回时。