--- tags: leetcode --- # [652. Find Duplicate Subtrees](https://leetcode.com/problems/find-duplicate-subtrees/) --- # My Solution ## The Key Idea for Solving This Coding Question DFS (recursion, postorder traversal) + hash map ## C++ Code ```cpp= /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<TreeNode *> findDuplicateSubtrees(TreeNode *root) { vector<TreeNode *> answer; unordered_map<string, int> subtreeCnt; dfs(root, subtreeCnt, answer); return answer; } private: string dfs(TreeNode *root, unordered_map<string, int> &subtreeCnt, vector<TreeNode *> &answer) { if (root == nullptr) { return "x,"; } string subtree = dfs(root->left, subtreeCnt, answer) + dfs(root->right, subtreeCnt, answer) + to_string(root->val) + ","; auto iter = subtreeCnt.find(subtree); if (iter == subtreeCnt.end()) { subtreeCnt[subtree] = 1; } else { if (iter->second == 1) { answer.push_back(root); } ++iter->second; } return subtree; } }; ``` ## Time Complexity $O(n)$ $n$ is the number of nodes in the binary tree referred by `root`. ## Space Complexity $O(H)$ $H$ is the height of the binary tree referred by `root`. # Miscellaneous <!-- # Test Cases ``` [1,2,3,4,null,2,4,null,null,4] ``` ``` [2,1,1] ``` ``` [2,2,2,3,null,3,null] ``` ``` [1,2,2,3,4,3,4,5,null,6,null,5,null,null,6] ``` ``` [2,1,3] ``` * wrong answer: ``` [10,2,22,1,12,1,1] ``` * wrong answer: ``` [0,0,0,0,null,null,0,0,0,0,0] ``` -->