寻找重复的子树
题目
思路
map巧妙统计。
代码
/**
* 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,int> f;
vector<TreeNode*> ans;
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
find(root);
return ans;
}
string find(TreeNode* root) {
if(root==NULL) return "#";
string s;
s=to_string(root->val)+' '+find(root->left)+' '+find(root->right);
if(f[s]==1) ans.push_back(root);
f[s]++;
return s;
}
};