寻找重复的子树,首先序列化,然后进行哈希映射,统计次数求解

一次哈希

由于序列化返回的字符串长度是Leetcode 652. 寻找重复的子树 - 图1的,所以整个算法的时间复杂度就是Leetcode 652. 寻找重复的子树 - 图2的

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10. * };
  11. */
  12. class Solution {
  13. public:
  14. unordered_map<string,int> hash;
  15. vector<TreeNode*> res;
  16. int cnt = 0;
  17. string dfs(TreeNode* root){
  18. if(!root) return "#";
  19. string left = dfs(root->left);
  20. string right = dfs(root->right);
  21. string tree = to_string(root->val)+","+left+","+right;
  22. hash[tree]++;
  23. if(hash[tree]==2) res.push_back(root);
  24. return tree;
  25. }
  26. vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
  27. // hash["#"]
  28. dfs(root);
  29. return res;
  30. }
  31. };

二次哈希

二次hash,之后时间复杂度为:Leetcode 652. 寻找重复的子树 - 图3

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10. * };
  11. */
  12. class Solution {
  13. public:
  14. int cnt = 0;
  15. vector<TreeNode*> res;
  16. unordered_map<string,int> hash; // 一次hash
  17. unordered_map<int,int> count; // 二次hash
  18. string dfs(TreeNode* root){
  19. if(!root) return to_string(hash["#"]);
  20. string left = dfs(root->left);
  21. string right = dfs(root->right);
  22. string tree = to_string(root->val)+','+left+','+right;
  23. if(!hash[tree]) hash[tree] = ++cnt;
  24. int t = hash[tree];
  25. count[t]++;
  26. if(count[t]==2) res.push_back(root);
  27. return to_string(t);
  28. }
  29. vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
  30. hash["#"] = ++cnt;
  31. dfs(root);
  32. return res;
  33. }
  34. };