Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
18 views3 pages

Practical No. - 5 - B - 1

Uploaded by

nikita.khawase
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views3 pages

Practical No. - 5 - B - 1

Uploaded by

nikita.khawase
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

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.")

You might also like