力扣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;
    }
}
相关推荐
sjsjs113 分钟前
【数据结构-字典树】力扣14. 最长公共前缀
数据结构·leetcode
python算法(魔法师版)21 分钟前
基于机器学习鉴别中药材的方法
深度学习·线性代数·算法·机器学习·支持向量机·数据挖掘·动态规划
JNU freshman1 小时前
力扣第435场周赛讲解
算法·leetcode·蓝桥杯
眼镜哥(with glasses)1 小时前
蓝桥杯python基础算法(2-2)——基础算法(B)——模拟(上)
算法
赵鑫亿3 小时前
7.DP算法
算法·dp
iqay3 小时前
【C语言】填空题/程序填空题1
c语言·开发语言·数据结构·c++·算法·c#
还有糕手3 小时前
算法【有依赖的背包】
算法·动态规划
pursuit_csdn4 小时前
力扣 347. 前 K 个高频元素
算法·leetcode
wen__xvn4 小时前
每日一题洛谷B3865 [GESP202309 二级] 小杨的 X 字矩阵c++
c++·算法·矩阵
makabaka_T_T4 小时前
25寒假算法刷题 | Day1 | LeetCode 240. 搜索二维矩阵 II,148. 排序链表
数据结构·c++·算法·leetcode·链表·矩阵