I have a Binary tree for a mathematical expression(infix), i want to convert directly this TREE to a postfix(Stack) can any body suggest the algorithm?
views:
237answers:
2
A:
Easy, each node is (Left, Right, Data).
Start with the first node. execute the algorithm for the left subtree if available and then execute the algorithm for the right subtree and then print the data.
TreeNode = ([TreeNode], Data, [TreeNode])
TreeToPostfix: [TreeNode] -> Data*
TreeToPostfix(nil) = []
TreeToPostfix((left, data, right)) ==
TreeToPostfix(left) ++ TreeToPostfix(right) ++ Data
For example:
+
/ \
* -
/ \ / \
2 3 4 5
Produces: 2 3 * 4 5 - +
Gamecat
2009-08-27 08:29:13
can u plz explain the approach as data will always be at lowset level of tree
Sam Rudolph
2009-08-27 08:32:09
Data in this case is both value and operator. My algorithm prduced prefix, but is now fixed to postfix.
Gamecat
2009-08-27 08:36:56
thanx Gamecat For the help..
Sam Rudolph
2009-08-27 08:39:21
+2
A:
What you’re searching for is known as post-order tree traversal:
postorder(node)
if node.left ≠ null then postorder(node.left)
if node.right ≠ null then postorder(node.right)
print node.value
Konrad Rudolph
2009-08-27 08:37:34