[leetcode-652-Find Duplicate Subtrees]

Posted hellowOOOrld

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode-652-Find Duplicate Subtrees]相关的知识,希望对你有一定的参考价值。

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.

思路:

将每一个节点的左子节点的值和右结点的值都存储下来,组成一个字符串,作为索引,将对应节点保存到map里。

string serialize(TreeNode* root,unordered_map<string,vector<TreeNode*> >& mp)
{
  if(root==nullptr) return "";
  string s= "(" + serialize(root->left,mp) + to_string(root->val) + serialize(root->right,mp) + ")";
  mp[s].push_back(root);
  return s;
}
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root)
{
    unordered_map<string,vector<TreeNode*> >mp;
    vector<TreeNode*>ret;
    serialize(root,mp);
    for(auto it = mp.begin();it != mp.end();it++)
    {
      if(it->second.size() > 1) ret.push_back(it->second[0]);
    }
    return ret;
} 

参考:

https://discuss.leetcode.com/topic/97601/c-clean-code

以上是关于[leetcode-652-Find Duplicate Subtrees]的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 652. Find Duplicate Subtrees

[LeetCode]652. Find Duplicate Subtrees找到重复树

Android 平台ping 对方ip返回 +3 duplicates (重复回应包)

分而治之检查重复项

将文件扩展名作为参数传递给powershell脚本

MySQLUnknown column 'column_name' in 'field list'