寻找重复的子树,首先序列化,然后进行哈希映射,统计次数求解
一次哈希
由于序列化返回的字符串长度是的,所以整个算法的时间复杂度就是
的
/*** 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:unordered_map<string,int> hash;vector<TreeNode*> res;int cnt = 0;string dfs(TreeNode* root){if(!root) return "#";string left = dfs(root->left);string right = dfs(root->right);string tree = to_string(root->val)+","+left+","+right;hash[tree]++;if(hash[tree]==2) res.push_back(root);return tree;}vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {// hash["#"]dfs(root);return res;}};
二次哈希
二次hash,之后时间复杂度为:
/*** 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:int cnt = 0;vector<TreeNode*> res;unordered_map<string,int> hash; // 一次hashunordered_map<int,int> count; // 二次hashstring dfs(TreeNode* root){if(!root) return to_string(hash["#"]);string left = dfs(root->left);string right = dfs(root->right);string tree = to_string(root->val)+','+left+','+right;if(!hash[tree]) hash[tree] = ++cnt;int t = hash[tree];count[t]++;if(count[t]==2) res.push_back(root);return to_string(t);}vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {hash["#"] = ++cnt;dfs(root);return res;}};
