题目描述:
Given a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of any oneof them.
Two trees are duplicate if they have the same structure with same node values.
Example 1:
1
/ \
2 3
/ / \
4 2 4
/
4
The following are two duplicate subtrees:
2
/
4
and
4
Therefore, you need to return above trees' root in the form of a list.
class Solution {
public:
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
unordered_map<string,int> hash;
vector<TreeNode*> result;
serialize(root,hash,result);
return result;
}
string serialize(TreeNode* root, unordered_map<string,int>& hash, vector<TreeNode*>& result)
{ // 将子树序列化,并统计次数,如果出现过一次,说明遇见了重复的子树
if(root==NULL) return "#";
// 注意中序遍历的序列化不是唯一的,即不同的子树可能有相同的序列,这是因为把空节点标为#的结果
// 例如[0,0,NULL]和[NULL,0,0]的中序遍历序列化之后是一样的:#/0/#/0/#,所以应该采用先序遍历或后序遍历
string s=serialize(root->left,hash,result)+"/"+serialize(root->right,hash,result)
+to_string(root->val);
if(hash.count(s))
{
// 次数必须为1,表示第二次出现这个子树应该加入结果中,之后如果出现多次都不会重复
if(hash[s]==1) result.push_back(root);
hash[s]++;
}
else hash[s]=1;
return s;
}
};