diff options
author | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
---|---|---|
committer | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
commit | d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch) | |
tree | 96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /find_duplicate_subtree.cpp | |
download | leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip |
initial
Diffstat (limited to 'find_duplicate_subtree.cpp')
-rw-r--r-- | find_duplicate_subtree.cpp | 30 |
1 files changed, 30 insertions, 0 deletions
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<TreeNode *> findDuplicateSubtrees(TreeNode *root) { + unordered_map<string, vector<TreeNode *>> map; + vector<TreeNode *> 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<string, vector<TreeNode *>> &map) { + string s = "(" + serialise(node->left, map) + to_string(node->val) + + serialise(node->right, map) + ")"; + map[s].push_back(node); + return s; + } +}; |