1. 程式人生 > 實用技巧 >【二叉樹思想】652. Find Duplicate Subtrees

【二叉樹思想】652. Find Duplicate Subtrees

問題:

給定一棵二叉樹,對所有節點為root的子樹,若存在重複的子樹。將該節點加入res。

Example 1:
Input: root = [1,2,3,4,null,2,4,null,null,4]
Output: [[2,4],[4]]

Example 2:
Input: root = [2,1,1]
Output: [[1]]

Example 3:
Input: root = [2,2,2,3,null,3,null]
Output: [[2,3],[3]]
 
Constraints:
The number of the nodes in the tree will be in the range [1, 10^4]
-200 <= Node.val <= 200

解法:

對每個節點:我們應該做什麼?

1. 看看以該節點為root的子樹,是什麼樣子的?-> 遞迴

2. 將1.中得到的子樹,在所有遍歷過的子樹all_subtrees中,進行對比。

3. 如果已經存在同樣的子樹:將該節點加入res

4. 如果不存在這樣的子樹:將該節點加入遍歷過的子樹all_subtrees群中

⚠️ 注意:

在第3步中,可能在res中,存入重複的子樹,

因此,在遍歷過的子樹all_subtrees中,記錄比對次數,當只比對過一次的時候,才加入res。

程式碼參考:

 1 /**
 2  * Definition for a binary tree node.
3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10 * }; 11 */ 12 class Solution { 13 public: 14 unordered_map<string, int> all_subtrees; 15 vector<TreeNode*> res; 16 //for each node: 17 //1. find one's tree -> get the tree all node 18 //2. use 1. to compare all_subtrees of the root. 19 //3. if there is a same tree in 2. , then res.append(this.node) 20 //4. else all_subtrees.append(this.node) 21 vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) { 22 traverse(root); 23 return res; 24 } 25 string traverse(TreeNode* root) { 26 if(!root) return string("#"); 27 //1. find one's tree -> get the tree all node 28 string left = traverse(root->left); 29 string right = traverse(root->right); 30 string mytree = left+","+right+","+to_string(root->val); 31 //2. use 1. to compare all_subtrees of the root. 32 if(all_subtrees.count(mytree)!=0) { 33 //3. if there is a same tree in 2. , then res.append(this.node) 34 if(all_subtrees[mytree]==1) res.push_back(root); 35 all_subtrees[mytree]++; 36 } else { 37 //4. else all_subtrees.append(this.node) 38 //all_subtrees[mytree]++; 39 all_subtrees[mytree]=1; 40 } 41 return mytree; 42 } 43 };