码迷,mamicode.com
首页 > 其他好文 > 详细

652. Find Duplicate Subtrees

时间:2018-12-02 12:02:23      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:val   div   roo   second   init   def   btree   ica   turn   

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    unordered_map<string, vector<TreeNode*>> s;
    vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
        dfs(root);
        vector<TreeNode*> res;
        for (auto & i : s) {
            if (i.second.size() > 1)
                res.push_back(i.second[0]);
        }
        return res;
    }
    string dfs(TreeNode* root) {
        if (root == NULL)   return "";
        string t = "(" + dfs(root->left) + to_string(root->val) + dfs(root->right) + ")";
        s[t].push_back(root);
        return t;
    }
};

 

652. Find Duplicate Subtrees

标签:val   div   roo   second   init   def   btree   ica   turn   

原文地址:https://www.cnblogs.com/JTechRoad/p/10052138.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!