class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def construct_expression_tree(prefix):
stack = []
# Start from the end of the prefix expression
for char in reversed(prefix):
# If character is an operand, push it to the stack
if char.isalpha():
stack.append(Node(char))
else:
# Operator node
node = Node(char)
# Pop two top nodes from the stack and make them children
if stack: node.left = stack.pop()
if stack: node.right = stack.pop()
# Push the current node back to the stack
stack.append(node)
# The root of the expression tree is the last item in the stack
return stack[-1]
def post_order_traversal_non_recursive(root):
if root is None:
return
stack = []
visited = set()
stack.append(root)
while stack:
current = stack[-1]
if current in visited:
stack.pop()
print(current.value, end=' ')
continue
visited.add(current)
if current.right:
stack.append(current.right)
if current.left:
stack.append(current.left)
def delete_tree(node):
if node is None:
return
# Deleting subtrees first
delete_tree(node.left)
delete_tree(node.right)
# Delete the current node
del node
# Example usage
prefix_expr = "+--a*bc/def"
root = construct_expression_tree(prefix_expr)
print("Post-order traversal of the constructed expression tree:")
post_order_traversal_non_recursive(root)
# Deleting the entire tree
delete_tree(root)
root = None # Ensure the reference to the tree's root is removed
print("\nTree deleted.")