652. 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 oneof 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.

先用preorder traversal把掃過的tree都serialize成string然後用一個hashmap紀錄遇過的tree,如果剛好遇到第2次的時候就把那個tree加到要回傳的vector裡。

// Preorder Traversal
string helper(TreeNode* node, unordered_map<string, int>& mp, vector<TreeNode*>& res) {
    if (!node) return "#";
    string str = to_string(node->val) + "," + helper(node->left, mp, res) + "," + helper(node->right, mp, res);
    if (++mp[str] == 2) res.push_back(node);
    return str;
}
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) { // time: O(n); space: O(n)
    unordered_map<string, int> mp;
    vector<TreeNode*> res;
    helper(root, mp, res);
    return res;
}

Last updated

Was this helpful?