多叉树遍历

来源:互联网 发布:css3 知乎 编辑:程序博客网 时间:2024/06/10 02:10
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 currentif __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()

这里写图片描述

0 0
原创粉丝点击