Find Duplicate Subtrees — LeetCode 652 Python Solution
MediumTreeDepth-First SearchHash TableBinary Tree
- Problem
- #652
- Pattern
- Tree Traversal
- Reading time
- 4 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- root = [1,2,3,4,null,2,4,null,null,4]
- Output
- [[2,4],[4]]
Python solution
Python
# 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
class Solution:
def findDuplicateSubtrees(
self, root: Optional[TreeNode]
) -> List[Optional[TreeNode]]:
def dfs(root):
if root is None:
return '#'
v = f'{root.val},{dfs(root.left)},{dfs(root.right)}'
counter[v] += 1
if counter[v] == 2:
ans.append(root)
return v
ans = []
counter = Counter()
dfs(root)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 652. Find Duplicate Subtrees is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
LeetCode 653Two Sum IV - Input is a BSTEasyLeetCode 508Most Frequent Subtree SumMediumLeetCode 863All Nodes Distance K in Binary TreeMediumLeetCode 865Smallest Subtree with all the Deepest NodesMediumLeetCode 987Vertical Order Traversal of a Binary TreeHardLeetCode 1110Delete Nodes And Return ForestMedium
Frequently asked questions
- How hard is LeetCode 652. Find Duplicate Subtrees?
- LeetCode 652. Find Duplicate Subtrees is rated Medium on LeetCode.
- What is the time complexity of LeetCode 652. Find Duplicate Subtrees?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 652. Find Duplicate Subtrees?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 652. Find Duplicate Subtrees cover?
- LeetCode 652. Find Duplicate Subtrees is tagged Tree, Depth-First Search, Hash Table and Binary Tree on LeetCode.