Given a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of anyone of 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.
lass Solution {
public:
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
unordered_map<string, vector<TreeNode *>> map;
vector<TreeNode *> dup;
serialize(root, map);
unordered_map<string, vector<TreeNode *>>::iterator it = map.begin();
for( ; it!=map.end(); it++)
{
if(it->second.size()>1)
dup.push_back(it->second[0]);
}
return dup;
}
string serialize(TreeNode * root, unordered_map<string, vector<TreeNode *>> &mp)
{
if(!root) return "";
string s="(" + serialize(root->left, mp) + to_string(root->val) + serialize(root->right, mp) + ")";
mp[s].push_back(root);
return s;
}
};
本文介绍了一种算法,用于在给定的二叉树中找出所有重复的子树结构,并仅返回每个重复子树的根节点。通过序列化二叉树的方法,将树的结构转换为字符串形式,进而利用哈希表来识别重复子树。
238

被折叠的 条评论
为什么被折叠?



