1. 程式人生 > >[leetcode-652-Find Duplicate Subtrees]

[leetcode-652-Find Duplicate Subtrees]

ive 思路 uno tar cat with spa DDU cond

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]