力扣652. 寻找重复的子树

Problem: 652. 寻找重复的子树

文章目录

题目描述

思路

1.利用二叉树的后序遍历 将原始的二叉树序列化 (之所以利用后序遍历 是因为其在归的过程中是会携带左右子树的节点信息,而这些节点信息正是该解法要利用的东西);

2.在一个哈希表中存储每一个序列化后子树和其出现的次数(初始时设为出现0次,每当有一次重复就将其次数加一);

3.将哈希表中出现次数大于等于1的子树的节点添加到一个结果集合中

复杂度

时间复杂度:

O ( n ) O(n) O(n);其中 n n n二叉树中节点的个数

空间复杂度:

O ( n ) O(n) O(n)

Code

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    // Record all subtrees and the number of occurrences
    Map<String, Integer> memo = new HashMap<>();
    // Record duplicate child root nodes
    List<TreeNode> res = new LinkedList<>();

    /**
     * Find Duplicate Subtrees
     *
     * @param root The root of binary tree
     * @return List<TreeNode>
     */
    public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
        traverse(root);
        return res;
    }

    /**
     * Find Duplicate Subtrees(Implementation function)
     *
     * @param root The root of binary tree
     * @return String
     */
    private String traverse(TreeNode root) {
        if (root == null) {
            return "#";
        }
        String left = traverse(root.left);
        String right = traverse(root.right);

        String subTree = left + "," + right + "," + root.val;

        int freq = memo.getOrDefault(subTree, 0);
        // Multiple repetitions will only be added to the result set once
        if (freq == 1) {
            res.add(root);
        }
        // Add one to the number of
        // occurrences corresponding to the subtree
        memo.put(subTree, freq + 1);
        return subTree;
    }
}
相关推荐
liulilittle14 分钟前
IP校验和算法:从网络协议到SIMD深度优化
网络·c++·网络协议·tcp/ip·算法·ip·通信
bkspiderx2 小时前
C++经典的数据结构与算法之经典算法思想:贪心算法(Greedy)
数据结构·c++·算法·贪心算法
中华小当家呐3 小时前
算法之常见八大排序
数据结构·算法·排序算法
沐怡旸3 小时前
【算法--链表】114.二叉树展开为链表--通俗讲解
算法·面试
一只懒洋洋4 小时前
K-meas 聚类、KNN算法、决策树、随机森林
算法·决策树·聚类
方案开发PCBA抄板芯片解密5 小时前
什么是算法:高效解决问题的逻辑框架
算法
songx_995 小时前
leetcode9(跳跃游戏)
数据结构·算法·游戏
小白狮ww6 小时前
RStudio 教程:以抑郁量表测评数据分析为例
人工智能·算法·机器学习
AAA修煤气灶刘哥6 小时前
接口又被冲崩了?Sentinel 这 4 种限流算法,帮你守住后端『流量安全阀』
后端·算法·spring cloud
kk”7 小时前
C语言快速排序
数据结构·算法·排序算法