Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive Postorder Traversal to List in Python?

Hello all—I'm a programming newcomer, and have the following very simple code here:

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

All I want is instead of printing the traversal I want to have the function store that information in an array or something of the like such that I can then use that information for other things

like image 423
Aaron Ramsey Avatar asked Nov 05 '13 17:11

Aaron Ramsey


People also ask

What is the recursive traversing of post-order traversal?

Recursive postorder traversal of a binary tree Suppose we use the function postorder(root) with root as an input parameter. Here we first process all nodes in the left subtree, then process all nodes in the right subtree, and at the end, we process the root node.

How do you do a post-order traversal Python?

Post-order TraversalFirst we traverse the left subtree, then the right subtree and finally the root node. In the below python program, we use the Node class to create place holders for the root node as well as the left and right nodes. Then we create a insert function to add data to the tree.

How do you traverse a binary tree in postorder traversal without recursion?

a) Push root's right child and then root to stack. b) Set root as root's left child. 2.2 Pop an item from stack and set it as root. a) If the popped item has a right child and the right child is at top of stack, then remove the right child from stack, push the root back and set root as root's right child.

What is Postorder transversal algorithm?

Postorder traversal is a kind of traversal in which we first traverse the left subtree in a postorder manner, then traverse the right subtree in a postorder manner and at the end visit the root node. For example, in the following tree: The postorder traversal will be 7→5→4→20→60→30→10.


1 Answers

You can do:

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

The inner function recurse takes care of traversing over the tree and the data is automatically added to data.

like image 106
Simeon Visser Avatar answered Nov 14 '22 23:11

Simeon Visser