652 Find Duplicate Subtrees

652. Find Duplicate Subtrees

1. Question

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

Therefore, you need to return above trees' root in the form of a list.

2. Implementation

(1) Post order traversal + HashMap

3. Time & Space Complexity

Post order traversal + HashMap: 时间复杂度: O(n), 空间复杂度: O(n)

Last updated

Was this helpful?