Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find out if two expression trees are equivalent using Python
When working with expression trees, we sometimes need to determine if two trees represent equivalent expressions. This involves checking whether both trees evaluate to the same result, even if their structure differs due to commutative properties of operations.
Expression trees store mathematical expressions where leaf nodes contain operands and internal nodes contain operators. Two trees are equivalent if they produce the same value when evaluated.
Algorithm Approach
The solution uses a frequency-counting approach for leaf nodes. Since the trees are equivalent if they have the same operands (regardless of order due to commutativity), we count the frequency of each leaf value in both trees and compare the results ?
Implementation
import collections
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def insert(temp, data):
que = []
que.append(temp)
while (len(que)):
temp = que[0]
que.pop(0)
if (not temp.left):
if data is not None:
temp.left = TreeNode(data)
else:
temp.left = TreeNode(0)
break
else:
que.append(temp.left)
if (not temp.right):
if data is not None:
temp.right = TreeNode(data)
else:
temp.right = TreeNode(0)
break
else:
que.append(temp.right)
def make_tree(elements):
tree = TreeNode(elements[0])
for element in elements[1:]:
insert(tree, element)
return tree
def solve(root1, root2):
dic1 = collections.defaultdict(int)
dic2 = collections.defaultdict(int)
def dfs(node, dic):
if not node:
return
if not node.left and not node.right: # Leaf node
dic[node.val] += 1
dfs(node.left, dic)
dfs(node.right, dic)
dfs(root1, dic1)
dfs(root2, dic2)
return dic1 == dic2
# Create expression trees
root1 = make_tree([1, '+', 2, '*', 3, '+', 4])
root2 = make_tree([2, '+', 1, '*', 4, '+', 3])
print(solve(root1, root2))
True
How It Works
The dfs() function traverses each tree and counts the frequency of leaf node values. The algorithm works because ?
- Leaf nodes represent the actual operands in the expression
- Commutative operations (like addition and multiplication) allow operands to be rearranged
- Same operand frequencies indicate equivalent expressions under commutative operations
Key Points
- Only leaf nodes are counted since they contain the actual values
- Internal nodes contain operators and don't affect equivalence for commutative operations
- Two dictionaries with identical key−value pairs indicate equivalent trees
- Time complexity is O(n) where n is the number of nodes
Conclusion
This approach efficiently determines expression tree equivalence by comparing leaf node frequencies. It works well for commutative operations where operand order doesn't affect the final result.
