LeetCode 652 寻找重复的子树

寻找重复的子树

题目

在这里插入图片描述

思路

map巧妙统计。

代码

/**
 * 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,int> f;
    vector<TreeNode*> ans;
    vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
        find(root);
        return ans;
    }
    string find(TreeNode* root) {
        if(root==NULL) return "#";
        string s;
        s=to_string(root->val)+' '+find(root->left)+' '+find(root->right);
        if(f[s]==1) ans.push_back(root);
        f[s]++;
        return s;
    }
};
发布了173 篇原创文章 · 获赞 6 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/shidonghang/article/details/102981927
今日推荐