給定一棵二叉樹,返回所有重復的子樹。對于同一類的重復子樹,你只需要返回其中任意一棵的根結點即可。
兩棵樹重復是指它們具有相同的結構以及相同的結點值。
示例 1:
? ? ? ? 1
? ? ? ?/ \
? ? ? 2 ? 3
? ? ?/ ? / \
? ? 4 ? 2 ? 4
? ? ? ?/
? ? ? 4
下面是兩個重復的子樹:? ? ? 2
? ? ?/
? ? 4
和? ? 4
因此,你需要以列表的形式返回上述重復子樹的根結點。來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/find-duplicate-subtrees
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
解法:
class Solution {
public:vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {vector<TreeNode*> res;unordered_map<string, int> m;helper(root, m, res);return res;}string helper(TreeNode* node, unordered_map<string, int>& m, vector<TreeNode*>& res) {if (!node) return "#";string str = to_string(node->val) + "," + helper(node->left, m, res) + "," + helper(node->right, m, res);if (m[str] == 1) res.push_back(node);++m[str];return str;}
};
?