Python中的递归Postorder遍历列表?

时间:2013-11-05 17:51:27

标签: python list tree tree-traversal

大家好 - 我是一名编程新手,并在此处提供以下非常简单的代码:

def postorder(T):
    if T != None:
        postorder(T.left)
        postorder(T.right)
        print T.data,

我想要的只是打印遍历我想让函数将信息存储在数组或类似的东西中,以便我可以将该信息用于其他事情

2 个答案:

答案 0 :(得分:7)

你可以这样做:

def postorder(tree):
    data = []

    def recurse(node)
        if not node:
            return
        recurse(node.left)
        recurse(node.right)
        data.append(node.data)

    recurse(tree)
    return data

内部函数recurse负责遍历树,数据自动添加到data

答案 1 :(得分:1)

您可以传入可调用对象,也可以编写生成器:

def postorder(T):
    if T != None:
        postorder(T.left)
        postorder(T.right)
        print T.data,

def postorder_func(T, f):
    if T != None:
        postorder_func(T.left, f)
        postorder_func(T.right, f)
        f(T.data)

def postorder_gen(T):
    if T != None:
        for i in postorder_gen(T.left):
            yield i
        for i in postorder_gen(T.right):
            yield i
        yield T.data


class T:
    def __init__(self, left = None, data = None, right = None):
        self.left = left
        self.data = data
        self.right = right

one_half = T(data=.5)
three_halves = T(data=1.5)
one = T(one_half, 1, three_halves)
three = T(data=3)
root = T(one, 2, three)

postorder(root)
print ""

a = []
postorder_func(root, a.append)
print a

a = list(postorder_gen(root))
print a

或者,单线解决方案:

def postorder_one(T):
    return [] if T is None else postorder_one(T.left)+[T.data]+postorder_one(T.right)