652. Find Duplicate Subtrees
Description
Difficulty: Medium
Related Topics: Hash Table, Tree, Depth-First Search, Binary Tree
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.
Example 1:
1 | Input: root = [1,2,3,4,null,2,4,null,null,4] |
Example 2:
1 | Input: root = [2,1,1] |
Example 3:
1 | Input: root = [2,2,2,3,null,3,null] |
Constraints:
- The number of the nodes in the tree will be in the range
[1, 5000]
-200 <= Node.val <= 200
Hints/Notes
- Serialize the (sub)tree to check if there’s duplicate
- Use map the avoid the duplicate in return, only push to res when freq[seri] == 1
Solution
Language: C++
1 | /** |