⬅ Previous Topic
Solve the Tree Isomorphism ProblemNext Topic ⮕
Check if Two Binary Trees are Mirror Images⬅ Previous Topic
Solve the Tree Isomorphism ProblemNext Topic ⮕
Check if Two Binary Trees are Mirror Imagesclass TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def hasDuplicateSubtrees(root):
seen = {}
duplicate = False
def serialize(node):
nonlocal duplicate
if not node:
return '#'
left = serialize(node.left)
right = serialize(node.right)
subtree = str(node.val) + ',' + left + ',' + right
# Only consider subtrees of size >= 2 (node with at least one child)
if node.left or node.right:
seen[subtree] = seen.get(subtree, 0) + 1
if seen[subtree] == 2:
duplicate = True
return subtree
serialize(root)
return duplicate
# Example usage:
if __name__ == '__main__':
# Construct a sample binary tree:
# 1
# / \
# 2 3
# / / \
# 4 2 4
# /
# 4
root = TreeNode(1, TreeNode(2, TreeNode(4)), TreeNode(3, TreeNode(2, TreeNode(4)), TreeNode(4)))
print(hasDuplicateSubtrees(root))
⬅ Previous Topic
Solve the Tree Isomorphism ProblemNext Topic ⮕
Check if Two Binary Trees are Mirror ImagesYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.