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
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With