leetcode 652. 寻找重复的子树

  1. 题目链接 https://leetcode-cn.com/problems/find-duplicate-subtrees/submissions/

  2. 题目描述

    1. 给定一棵二叉树,返回所有重复的子树。对于同一类的重复子树,你只需要返回其中任意一棵的根结点即可。

      两棵树重复是指它们具有相同的结构以及相同的结点值。

    2.         1
             / \
            2   3
           /   / \
          4   2   4
             /
            4
      

      下面是两个重复的子树:

            2
           /
          4
      

          4
      
  3. 解题思路

    1. 通过map记录每颗子树先序遍历或者后序遍历的结果, 找到所有遍历结果相同的子树。
    2. 结构不同的子树单纯的后序或是先序遍历可能结果一样,我们可以做一下特殊处理,即空树的遍历结果为某个特殊字符,这样一颗树的遍历结果就被唯一限定了。
  4. 代码

    1. 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
              

       

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

       

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值