标签:treenode def nod ica binary red pre find turn
https://leetcode-cn.com/problems/find-duplicate-subtrees/
中文题
将每一颗子树转换成字符串,然后通过unordered_map去重即可(map的速度较慢)
AC代码:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) { 13 14 vector<TreeNode*>ans; 15 unordered_map<string,int>vis; 16 17 dfs(root, ans, vis); 18 19 return ans; 20 } 21 string dfs(TreeNode* root, vector<TreeNode*>&ans, unordered_map<string,int>&vis){ 22 23 if(root == NULL) 24 return "#"; 25 26 string tmp = to_string(root->val) + dfs(root->left, ans, vis) + dfs(root->right, ans, vis); 27 28 if(vis[tmp] == 1) 29 ans.push_back(root); 30 vis[tmp]++; 31 32 return tmp; 33 } 34 };
标签:treenode def nod ica binary red pre find turn
原文地址:https://www.cnblogs.com/letlifestop/p/11517008.html