题目链接
注意事项
将一颗子树按照先序遍历的方式组装成一个字符串,方便进行比较。
使用unordered_map进行数量判断。
代码
/**
* 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 {
private:
unordered_map<string, int> ump;
vector<TreeNode*> ans;
public:
string dfs(TreeNode* root){
if (root == nullptr){
return "";
}
string ss = to_string(root->val) + "#" + dfs(root->left) + "#" + dfs(root->right);
ump[ss]++;
if (ump[ss] == 2){
ans.push_back(root);
}
return ss;
}
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
dfs(root);
return ans;
}
};
标签:right,TreeNode,val,nullptr,子树,652,root,LeetCode,left
From: https://www.cnblogs.com/shixuanliu/p/16659266.html