首页 > 其他 > 详细

652. Find Duplicate Subtrees

时间:2018-12-02 10:55:40      阅读:283      评论:0      收藏:0      [点我收藏+]
/**
 * 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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!