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.
解析
找到二叉树中重复的子树根节点。
解法
利用后序遍历以及数组序列化为字符串,并设置一个出现字符串到其出现次数的映射。得到一个序列化字符串,如果其出现次数为1,加入res中,这样保证只会出现一个重复的节点被加入。
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;
}
};