LeetCode Problem 652: Find Duplicate Subtrees
Given the root of a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of any one of them.
Two trees are duplicate if they have the same structure with the same node values.
Input: root = [1,2,3,4,null,2,4,null,null,4]
Output: [[2,4],[4]]
To identify duplicate subtrees:
To implement this:
from collections import defaultdict
from typing import List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def findDuplicateSubtrees(root: TreeNode) -> List[TreeNode]:
# This dictionary will store the serialized subtree and its count
trees = defaultdict(int)
duplicates = []
def serialize(node):
if not node:
return "#"
# Serialize current subtree
subtree = f"{node.val},{serialize(node.left)},{serialize(node.right)}"
# Record the occurrence of the subtree
trees[subtree] += 1
# If it has been seen exactly twice (to avoid adding the same root multiple times)
if trees[subtree] == 2:
duplicates.append(node)
return subtree
serialize(root)
return duplicates
This approach efficiently captures duplicate subtrees using serialization and tracking their counts, ensuring an optimal solution.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?