首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >N叉树的后序遍历

N叉树的后序遍历
EN

Stack Overflow用户
提问于 2019-04-10 06:26:44
回答 1查看 2.6K关注 0票数 2

我需要以下代码的帮助来回答。我试图使用堆栈而不是递归在n进制树上执行postorder遍历,因为python有1000个递归限制。我为极客在极客身上找到了相同的"https://www.geeksforgeeks.org/iterative-preorder-traversal-of-a-n-ary-tree/“命令遍历的代码。但我无法把它转到邮购处去。任何帮助都会很好。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-10 06:34:49

下面是我使用的带有iteration版本的stack

代码语言:javascript
复制
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.children = []

def postorder_traversal_iteratively(root: 'TreeNode'):
    if not root:
        return []
    stack = [root]
    # used to record whether one child has been visited
    last = None

    while stack:
        root = stack[-1]
        # if current node has no children, or one child has been visited, then process and pop it
        if not root.children or last and (last in root.children):
            '''
            add current node logic here
            '''
            print(root.val, ' ', end='')

            stack.pop()
            last = root
        # if not, push children in stack
        else:
            # push in reverse because of FILO, if you care about that
            for child in root.children[::-1]:
                stack.append(child)

测试代码和输出:

代码语言:javascript
复制
n1 = TreeNode(1)
n2 = TreeNode(2)
n3 = TreeNode(3)
n4 = TreeNode(4)
n5 = TreeNode(5)
n6 = TreeNode(6)
n7 = TreeNode(7)
n8 = TreeNode(8)
n9 = TreeNode(9)
n10 = TreeNode(10)
n11 = TreeNode(11)
n12 = TreeNode(12)
n13 = TreeNode(13)

n1.children = [n2, n3, n4]
n2.children = [n5, n6]
n4.children = [n7, n8, n9]
n5.children = [n10]
n6.children = [n11, n12, n13]

postorder_traversal_iteratively(n1)

可视化n叉树和输出:

代码语言:javascript
复制
                   1
                 / | \
                /  |   \
              2    3     4
             / \       / | \
            5    6    7  8  9
           /   / | \ 
          10  11 12 13

# output: 10  5  11  12  13  6  2  3  7  8  9  4  1  

另一种方法是修改结果,例如将结果插入头。

它效率较低,但易于编码。您可以在这里中找到一个版本

我在我的github中总结了像上面这样的算法的code templates

如果您对它感兴趣,请注意:模板

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55606017

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档