寻找重复的子树(dfs)

题目连接:

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 };

 

posted @ 2019-09-13 15:57  Let_Life_Stop  阅读(291)  评论(0编辑  收藏  举报