import nltk.tree as tree
# 递归遍历
def test(t):
if isinstance(t, str):
print t
else:
for i in range(len(t)):
test(t[len(t)-i-1])
# 非递归遍历
def test_2(t):
stack = []
stack.append(t)
current = ""
while stack:
current = stack.pop()
if isinstance(current, tree.Tree):
for i in range(len(current)):
stack.append(current[i])
elif isinstance(current, str):
# print "[输出] ",current
print current
if __name__ == "__main__":
C = tree.Tree("C", ["E", "F"])
B = tree.Tree("B", [C, "D"])
H = tree.Tree("H", ["M", "N"])
A = tree.Tree("A", ["G", H])
root = tree.Tree("Root", [A, B])
print root[0]
print root.height()
print len(root)
print type(root)
test(root)
test_2(root)
root.draw()
多叉树遍历
最新推荐文章于 2023-10-18 09:58:52 发布