力扣(LeetCode)算法_C++——寻找重复的子树

给你一棵二叉树的根节点 root ,返回所有 重复的子树 。

对于同一类的重复子树,你只需要返回其中任意 一棵 的根结点即可。

如果两棵树具有 相同的结构 和 相同的结点值 ,则认为二者是 重复 的。

示例 1:

输入:root = [1,2,3,4,null,2,4,null,null,4]

输出:[[2,4],[4]]

示例 2:

输入:root = [2,1,1]

输出:[[1]]

示例 3:

输入:root = [2,2,2,3,null,3,null]

输出:[[2,3],[3]]

cpp 复制代码
class Solution {
public:
    vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
        dfs(root);
        return {repeat.begin(), repeat.end()};
    }

    string dfs(TreeNode* node) {
        if (!node) {
            return "";
        }
        string serial = to_string(node->val) + "(" + dfs(node->left) + ")(" + dfs(node->right) + ")";
        if (auto it = seen.find(serial); it != seen.end()) {
            repeat.insert(it->second);
        }
        else {
            seen[serial] = node;
        }
        return serial;
    }

private:
    unordered_map<string, TreeNode*> seen;
    unordered_set<TreeNode*> repeat;
};
相关推荐
报错小能手1 天前
C++笔记——STL map
c++·笔记
思麟呀1 天前
Linux的基础IO流
linux·运维·服务器·开发语言·c++
星释1 天前
Rust 练习册 :Pythagorean Triplet与数学算法
开发语言·算法·rust
星释1 天前
Rust 练习册 :Nth Prime与素数算法
开发语言·算法·rust
多喝开水少熬夜1 天前
Trie树相关算法题java实现
java·开发语言·算法
QT 小鲜肉1 天前
【QT/C++】Qt定时器QTimer类的实现方法详解(超详细)
开发语言·数据库·c++·笔记·qt·学习
WBluuue1 天前
数据结构与算法:树上倍增与LCA
数据结构·c++·算法
bruk_spp1 天前
牛客网华为在线编程题
算法
呆瑜nuage1 天前
C++之红黑树
c++
亮剑20181 天前
第2节:程序逻辑与控制流——让程序“思考”
开发语言·c++·人工智能