zoukankan      html  css  js  c++  java
  • Java实现 LeetCode 652 寻找重复的子树(两个map的DFS)

    652. 寻找重复的子树

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

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

    示例 1:

     1
       / 
      2   3
     /   / 
    4   2   4
       /
      4
    

    下面是两个重复的子树:

          2
         /
        44
    

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

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
      private int treeId = 100;
        //这个用来保存树得,用一个id去替换树
        private Map<String, Integer> tree = new HashMap<>();
        //下面这个是用上面树换的id来保存次数得,只有两次得时候才会加入到下面得list里面
        private Map<Integer, Integer> count = new HashMap<>();
        private List<TreeNode> res;
    
        public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
            res = new ArrayList<>();
            this.dfs(root);
            return res;
        }
    
       
    
        private int dfs(TreeNode node){
            if(node == null) return 0;
    
            String content = new StringBuilder().append(node.val).append(",").append(this.dfs(node.left)).append(",").append(this.dfs(node.right)).toString();
    
            Integer id = tree.get(content);
            if(id == null) {
                id = treeId++;
                tree.put(content, id);
            }
    
            int num = count.getOrDefault(id, 0);
            count.put(id, ++num);
    
            if(num == 2) {
                res.add(node);
            }
            return id;
        }
    
    }
    
  • 相关阅读:
    xx
    office 2016 下载链接
    Revit 2019 下载链接
    AE cc 2019 下载链接
    Premiere Pro cc 2019 下载链接
    Photoshop cc 2019 下载链接
    百度云单机版、软件包及教程
    Visual Studio 2017 软件包及教程
    归并排序:逆序对问题
    归并排序:小和问题
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13074843.html
Copyright © 2011-2022 走看看