美文网首页
[刷题防痴呆] 0652 - 寻找重复的子树 (Find Dup

[刷题防痴呆] 0652 - 寻找重复的子树 (Find Dup

作者: 西出玉门东望长安 | 来源:发表于2022-02-25 00:10 被阅读0次

题目地址

https://leetcode.com/problems/find-duplicate-subtrees/

题目描述

652. Find Duplicate Subtrees

Given the root of a binary tree, return all duplicate subtrees.

For each kind of duplicate subtrees, you only need to return the root node of any one of them.

Two trees are duplicate if they have the same structure with the same node values.

 

Example 1:


Input: root = [1,2,3,4,null,2,4,null,null,4]
Output: [[2,4],[4]]
Example 2:


Input: root = [2,1,1]
Output: [[1]]
Example 3:


Input: root = [2,2,2,3,null,3,null]
Output: [[2,3],[3]]

思路

  • 二叉树的序列化, 前序或者后序都可以.
  • 如果当前子树已经在map中出现一次, 则将其加入到res中.
  • 之后当前子树如果再次出现, 则不加入到res.

关键点

代码

  • 语言支持: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 {

    Map<String, Integer> map = new HashMap<>();
    List<TreeNode> res = new ArrayList<>();
    public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
        traverse(root);
        return new ArrayList<>(res);
    }

    private String traverse(TreeNode node) {
        if (node == null) {
            return "#";
        }
        String left = traverse(node.left);
        String right = traverse(node.right);
        String str = node.val + "," + left + "," + right;
        int count = map.getOrDefault(str, 0);
        if (count == 1) {
            res.add(node);
        }
        map.put(str, count + 1);
        return str;
    }
}

相关文章

网友评论

      本文标题:[刷题防痴呆] 0652 - 寻找重复的子树 (Find Dup

      本文链接:https://www.haomeiwen.com/subject/vflzhrtx.html