From 63af3ba10d48774975bc30aeba407778ebdaf955 Mon Sep 17 00:00:00 2001 From: Eatswap Date: Wed, 1 Mar 2023 21:09:35 +0800 Subject: [PATCH] add: 230228 --- cpp/2302/230228.cpp | 56 +++++++++++++++++++++++++++++++++++++++++ cpp/2302/CMakeLists.txt | 2 +- 2 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 cpp/2302/230228.cpp diff --git a/cpp/2302/230228.cpp b/cpp/2302/230228.cpp new file mode 100644 index 0000000..3542c63 --- /dev/null +++ b/cpp/2302/230228.cpp @@ -0,0 +1,56 @@ +#include +#include +#include + +struct TreeNode { + int val; + TreeNode* left; + TreeNode* right; + + explicit TreeNode(int x = 0, TreeNode* left = nullptr, TreeNode* right = nullptr) : val(x), left(left), right(right) {} +}; + +/** + * 652. Find Duplicate Subtrees + * + * Given the root of a binary tree, return all duplicate subtrees. + * For each kind of duplicate subtrees, you only need to return the root node of any one of them. + * Two trees are duplicate if they have the same structure with the same node values. + */ + +class Solution { +private: + std::unordered_map strToNode; + std::unordered_map strCnt; + + // Pre-order + std::string toStr(TreeNode* r) { + if (!r) + return ""; + auto ret = std::to_string(r->val) + .append("(") + .append(toStr(r->left)) + .append(")(") + .append(toStr(r->right)) + .append(")"); + strToNode[ret] = r; + ++strCnt[ret]; + return ret; + } + +public: + std::vector findDuplicateSubtrees(TreeNode* r) { + toStr(r); + std::vector ret; + for (const auto& [str, c] : strCnt) { + if (c <= 1) + continue; + ret.push_back(strToNode[str]); + } + return ret; + } +}; + +int main() { + return 0; +} diff --git a/cpp/2302/CMakeLists.txt b/cpp/2302/CMakeLists.txt index da0a23c..c2dddaa 100644 --- a/cpp/2302/CMakeLists.txt +++ b/cpp/2302/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2302) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2302 230228-CN.cpp) +ADD_EXECUTABLE(2302 230228.cpp)