简体   繁体   中英

Postorder traversal of an n ary tree

I need help with the following code to answer. I am trying to perform a postorder traversal on an n-ary tree using stacks instead of recursion because python has a limit of 1000 recursions. I found code for preorder traversal for the same " https://www.geeksforgeeks.org/iterative-preorder-traversal-of-an-ary-tree/ " on geeks for geeks. But i am unable to covert it to postorder. Any help will be great.

Here is a iteration version with stack I used:

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)

test code & output:

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)

visual n-ary tree and output:

                   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  

and another idea to do postorder is changing the result, such as insert the result to head.

it is less effecient, but easy to coding. you can find a version in here


I have summarize code templates for algorithm like above in my github.
Watch it if you are interested in: https://github.com/recnac-itna/Code_Templates

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM