力扣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;
    }
}
相关推荐
Frostnova丶1 分钟前
(10)LeetCode 560. 和为K的子数组
算法·leetcode·哈希算法
AI专业测评5 分钟前
2026年AI写作软件底层技术全景解析:长篇AI写网文的工程化实践与AI消痕算法基准测试
人工智能·算法·ai写作
2401_8845632411 分钟前
高性能日志库C++实现
开发语言·c++·算法
葳_人生_蕤11 分钟前
hot100——226.翻转二叉树
算法
handler0116 分钟前
基础算法:BFS
开发语言·数据结构·c++·学习·算法·宽度优先
2401_8795034117 分钟前
C++中的状态模式实战
开发语言·c++·算法
不当菜鸡的程序媛18 分钟前
神经网络——bias 偏置项(bias term) 或者截距项(intercept term)
人工智能·神经网络·算法
Aawy12018 分钟前
自定义字面量实战
开发语言·c++·算法
无尽的罚坐人生20 分钟前
hot 100 200. 岛屿数量
算法·dfs
j_xxx404_24 分钟前
LeetCode模拟算法精解II:外观数列与数青蛙
数据结构·c++·算法·leetcode