Skip to content

Latest commit

 

History

History
 
 

652. Find Duplicate Subtrees

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

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.

Companies:
Uber, Amazon, Google, Microsoft

Related Topics:
Tree

Similar Questions:

Solution 1.

// OJ: https://leetcode.com/problems/find-duplicate-subtrees/
// Author: github.com/lzl124631x
// Time: O(N^2) since string concatenation takes O(N) time on average
// Space: O(N^2) since string take O(N) space on average
// Ref: https://leetcode.com/problems/find-duplicate-subtrees/solution/
class Solution {
private:
    unordered_map<string, int> treeToCnt;
    vector<TreeNode*> ans;
    string collect(TreeNode *node) {
        if (!node) return "#";
        string s = to_string(node->val) + "," + collect(node->left) + "," + collect(node->right);
        if (treeToCnt[s] == 1) ans.push_back(node);
        treeToCnt[s]++;
        return s;
    }
public:
    vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
        collect(root);
        return ans;
    }
};