zoukankan      html  css  js  c++  java
  • Leetcode 652.寻找重复的子树

    寻找重复的子树

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

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

    下面是两个重复的子树:

    因此,你需要以列表的形式返回上述重复子树的根结点。

    思路

    Intuition

    We can serialize each subtree. For example, the tree

       1
    
      / 
    
     2   3
    
        / 
    
       4   5
    

    can be represented as the serialization 1,2,#,#,3,4,#,#,5,#,#, which is a unique representation of the tree.

    Algorithm

    Perform a depth-first search, where the recursive function returns the serialization of the tree. At each node, record the result in a map, and analyze the map after to determine duplicate subtrees.

     1 class Solution {
     2     Map<String, Integer> count;
     3     List<TreeNode> ans;
     4     public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
     5         count = new HashMap();
     6         ans = new ArrayList();
     7         collect(root);
     8         return ans;
     9     }
    10 
    11     public String collect(TreeNode node) {
    12         if (node == null) return "#";
    13         String serial = node.val + "," + collect(node.left) + "," + collect(node.right);
    14         count.put(serial, count.getOrDefault(serial, 0) + 1);
    15         if (count.get(serial) == 2)
    16             ans.add(node);
    17         return serial;
    18     }
    19 }

  • 相关阅读:
    hdu 5253 最小生成树
    hdu5248 序列变换
    bjfu1299 stl使用
    bjfu1277 简单递归
    bjfu1262 优先队列
    bjfu1287字符串输出的大水题
    bjfu1281
    bjfu1253 最大上升子序列和
    [转][Unity3D]引擎崩溃、异常、警告、BUG与提示总结及解决方法
    Unity3d 中 将远程 MySQL 数据库转换为本地 Sqlite
  • 原文地址:https://www.cnblogs.com/kexinxin/p/10383085.html
Copyright © 2011-2022 走看看