}voidSubTreeStr(TreeNode* root1,string& str){// 考虑空节点,才能保证先序遍历的唯一性if(root1 ==NULL) { str +="NULL"; }else{ str += to_string(root1->val); SubTreeStr(root1->left, str); SubTreeStr(root1->right, str); } }vector<TreeNode*> sub1, res;map<string,int> count;...
mp[s].push_back(subtree[i]); } else{ mp.insert(pair<string,vector<TreeNode*>>(s,vector<TreeNode*>(1,subtree[i]))); } } subtree.clear(); map<string,vector<TreeNode*>>::iteratorit; for(it=mp.begin();it!=mp.end();it++) { if(it->second.size()>1) { subtree.push_back(i...
&subTree, &res)6returnres7}89privatefunc helper(_ root: TreeNode?, _ subTree: inout [String: Int], _ res: inout [TreeNode?]) ->String {10guard let root = rootelse{return"#"}11let serializedString ="\(String
[LeetCode] 652. Find Duplicate Subtrees Given therootof 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 the same node values. Examp...
File metadata and controls Code Blame 16 lines (16 loc) · 415 Bytes Raw class Solution { func containsDuplicate(_ nums: [Int]) -> Bool { // Solution 1 Use Set return !(Set<Int>(nums).count == nums.count) // Solution 2 Use HashMap var map = [Int: Int]() for num in nu...
题目并不难,把每个subtree的根节点存入一个HashMap中,然后递归判断root是否跟HashMap中的节点为duplicate。但这样计算会TLE,因为判断两个TreeNode是否为duplicate的代价比较大。比较方便的做法是将tree序列化成String,然后判断String是否相同即可。 /** * Definition for a binary tree node. ...
Therefore, you need to return above trees’ root in the form of a list. 思路: Intuition We can serialize each subtree. For example, the tree \ 2 3 / \ 1. 2. 3. can be represented as the serialization 1,2,#,#,3,4,#,#,5,#,#, which is a unique representation of the tree....
给每个subtree赋一个unique id,如果两个子树的id相同,说明duplicate。 需要用两个hashmap,一个把subtree serialize成string,存<string, id>,另一个计数,每个id出现多少次。最后遍历计数map,如果出现两次就放进res里 time: O(n), space: O(n) /*** Definition for a binary tree node. ...
* TreeNode(int x) : val(x), left(NULL), right(NULL) {} * };*///We can serialize each subtree. Perform a depth-first search, where the recursive function returns the serialization of the tree. At each node, record the result in a map, and analyze the map after to determine dupl...
Do preorder serialization in subtree and see this serialization happens before. Use a HashMap to maintain the frequency of serialization. Time Complexity: O(n). Space: O(n). AC Java: 1/**2* Definition for a binary tree node.3* public class TreeNode {4* int val;5* TreeNode left;6...