Problem description
Given 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 same node values.
Example 1:
1
/ \
2 3
/ / \
4 2 4
/
4
The following are two duplicate subtrees:
2
/
4
and
4
Therefore, you need to return above trees' root in the form of a list.
Solution
- We keep a dictionary of serialized trees. During dfs visit, if we found a node’s serialized string in the dictionary and its count is one (found it second time), we add the node to result. Else we increment the count of the serialized node by 1
Below is my python implementation
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findDuplicateSubtrees(self, root: TreeNode) -> List[TreeNode]:
sn = collections.defaultdict(int)
ans = []
def dfs(root:TreeNode)->str:
if not root:
return ""
left = dfs(root.left)
right = dfs(root.right)
res = "("+left+")"+str(root.val)+"("+right+")"
if res in sn and sn[res] == 1:
ans.append(root)
sn[res] += 1
return res
dfs(root)
return ans