-
题目链接 https://leetcode-cn.com/problems/find-duplicate-subtrees/submissions/
-
题目描述
-
给定一棵二叉树,返回所有重复的子树。对于同一类的重复子树,你只需要返回其中任意一棵的根结点即可。
两棵树重复是指它们具有相同的结构以及相同的结点值。
-
1 / \ 2 3 / / \ 4 2 4 / 4
下面是两个重复的子树:
2 / 4
和
4
-
-
解题思路
- 通过map记录每颗子树先序遍历或者后序遍历的结果, 找到所有遍历结果相同的子树。
- 结构不同的子树单纯的后序或是先序遍历可能结果一样,我们可以做一下特殊处理,即空树的遍历结果为某个特殊字符,这样一颗树的遍历结果就被唯一限定了。
-
代码
- python
class Solution: def findDuplicateSubtrees(self, root: TreeNode) -> List[TreeNode]: if not root: return [] m = {} ans = [] def _dfs(root): if not root: return "-" nonlocal ans, m path = "{}{}{}".format(_dfs(root.left), _dfs(root.right), root.val) if path in m and m[path] == 1: ans.append(root) m[path] = m.get(path, 0) + 1 return path _dfs(root) return ans
- c++
class Solution { public: vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) { map<string, int> m; vector<TreeNode*> res; _dfs(root, m, res); return res; } string _dfs(TreeNode* root, map<string, int>& m, vector<TreeNode*>& res){ if (not root) return "-"; string path = to_string(root->val) + _dfs(root->left, m, res) + _dfs(root->right, m, res); if (m[path] == 1) res.push_back(root); m[path] = m[path] + 1; return path; } };
- python
leetcode 652. 寻找重复的子树
最新推荐文章于 2023-06-06 11:22:21 发布