652.Find-Duplicate-Subtrees

652. Find Duplicate Subtrees

题目地址

https://leetcode.com/problems/find-duplicate-subtrees/

题目描述

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.

代码

Approach #1 DFS

Time: O(N^2) where N is the number of nodes in the tree. We visit each node once, but each creation of serial may take O(N) work.

Space: O(N^2) the size of count

Approach #2 Unique Identifier

Time: O(N log N)

Space: O(N)

Last updated

Was this helpful?