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 }

  • 相关阅读:
    探究操作系统的内存分配(malloc)对齐策略
    三十一个实用的小常识
    防止网页后退
    郁闷的一天
    脑袋不行
    家的开张
    猴子定律
    赴微软onsite!谁有C++/HTML/JavaScript开发工程师推荐?
    卡马克的求平方根函数代码的陷阱
    动作游戏自定义技能探讨
  • 原文地址:https://www.cnblogs.com/kexinxin/p/10383085.html
Copyright © 2011-2022 走看看