}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;...
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 1. 2. ...
&subTree, &res)6returnres7}89privatefunc helper(_ root: TreeNode?, _ subTree: inout [String: Int], _ res: inout [TreeNode?]) ->String {10guard let root = rootelse{return"#"}11let serializedString ="\(String
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的根节点存入一个HashMap中,然后递归判断root是否跟HashMap中的节点为duplicate。但这样计算会TLE,因为判断两个TreeNode是否为duplicate的代价比较大。比较方便的做法是将tree序列化成String,然后判断String是否相同即可。 /** * Definition for a binary tree node. ...
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 * ...
[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....
* 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...