首页 > 其他 > 详细

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

时间:2020-10-18 17:40:51      阅读:25      评论:0      收藏:0      [点我收藏+]

问题:

给定一棵二叉树,对所有节点为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 };

 

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

原文:https://www.cnblogs.com/habibah-chang/p/13835844.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!