/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: unordered_map<string, vector<TreeNode*>> s; vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) { dfs(root); vector<TreeNode*> res; for (auto & i : s) { if (i.second.size() > 1) res.push_back(i.second[0]); } return res; } string dfs(TreeNode* root) { if (root == NULL) return ""; string t = "(" + dfs(root->left) + to_string(root->val) + dfs(root->right) + ")"; s[t].push_back(root); return t; } };
原文地址:https://www.cnblogs.com/JTechRoad/p/10052138.html
时间: 2024-09-29 09:54:46