652. Find Duplicate Subtrees
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.
Approach
题目大意:要求你在二叉树中找到相同的子树,包括叶子节点。
思路方法:对树进行序列化处理,中间过程可以获得以每个结点作为根的子树序列,由此判断这些子树序列是否重复,重复则放进vector中。
Code
class Solution {
public:
vector<TreeNode*> nums;
unordered_map<string, int>unmp;
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
Search(root);
return nums;
}
string Search(TreeNode* root) {
if (root == nullptr)return "#";
string str = to_string(root->val) + "," + Search(root->left) + "," + Search(root->right);
unmp[str]++;
if (unmp[str] == 2) {
nums.push_back(root);
}
return str;
}
};