I'm posting my code for a LeetCode problem copied here. If you have time and would like to review, please do so. Thank you!
Problem
Given 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 same node values.
Example 1:
1 / \ 2 3 / / \ 4 2 4 / 4
The following are two duplicate subtrees:
2 / 4
and
4
Therefore, you need to return above trees' root in the form of a list.
Code
#include <vector> #include <unordered_map> #include <string> class Solution { public: std::vector<TreeNode *> findDuplicateSubtrees(TreeNode *root) { std::unordered_map<string, std::vector<TreeNode *>> nodes_map; std::vector<TreeNode *> duplicates; this->serialize(root, nodes_map); for (auto iter = nodes_map.begin(); iter != nodes_map.end(); iter++) { if (iter->second.size() > 1) { duplicates.push_back(iter->second[0]); } } return duplicates; } private: std::string serialize(TreeNode *node, std::unordered_map<std::string, std::vector<TreeNode *>> &nodes_map) { if (!node) { return ""; } std::string serialized = "[" + serialize(node->left, nodes_map) + std::to_string(node->val) + serialize(node->right, nodes_map) + "]"; nodes_map[serialized].push_back(node); return serialized; } };
Reference
LeetCode has a template for answering questions. There is usually a class named Solution
with one or more public
functions which we are not allowed to rename. For this question, the template is:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) { } };