From d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa Mon Sep 17 00:00:00 2001 From: jack <0x6A73@pm.me> Date: Fri, 14 Jun 2024 13:13:15 -0600 Subject: initial --- find_duplicate_subtree.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 find_duplicate_subtree.cpp (limited to 'find_duplicate_subtree.cpp') diff --git a/find_duplicate_subtree.cpp b/find_duplicate_subtree.cpp new file mode 100644 index 0000000..5880fc8 --- /dev/null +++ b/find_duplicate_subtree.cpp @@ -0,0 +1,30 @@ +// 652. Find Duplicate Subtrees +#include "leetcode.h" + +/* + * given 'root' of a binary tree, return all duplicate subtrees. for each kind + * of duplicate, only 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 { +public: + vector findDuplicateSubtrees(TreeNode *root) { + unordered_map> map; + vector dups; + serialise(root, map); + for (auto it = map.begin(); it != map.end(); it++) + if (it->second.size() > 1) + dups.push_back(it->second[0]); + return dups; + } + +private: + string serialise(TreeNode *node, + unordered_map> &map) { + string s = "(" + serialise(node->left, map) + to_string(node->val) + + serialise(node->right, map) + ")"; + map[s].push_back(node); + return s; + } +}; -- cgit v1.2.3