LeetCode(652):寻找重复的子树 Find Duplicate Subtrees(Java)

2019.11.12 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)

github:https://github.com/ChopinXBP/LeetCode-Babel

这题需要借助哈希表对已遍历的子树进行存储,为了避免重复计算,哈希表选取的key值可以选取序列化后的二叉树,通过后序遍历递归进行。


传送门:寻找重复的子树

Given 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 same node values.

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

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

示例 1:
        1
       / \
      2   3
     /   / \
    4   2   4
       /
      4
下面是两个重复的子树:

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


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 *
 * Given 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 same node values.
 * 给定一棵二叉树,返回所有重复的子树。对于同一类的重复子树,你只需要返回其中任意一棵的根结点即可。
 * 两棵树重复是指它们具有相同的结构以及相同的结点值。
 *
 */

public class FindDuplicateSubtrees {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) {
            val = x;
        }
    }

    //二叉树序列化+哈希表
    public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
        ArrayList<TreeNode> result = new ArrayList<>();
        Solution(root, new HashMap<>(), result);
        return result;
    }

    private String Solution(TreeNode root, HashMap<String, Integer> map, ArrayList<TreeNode> result){
        if(root == null){
            return "#";
        }
        //后序遍历序列化的二叉树
        String serial = root.val + "," + Solution(root.left, map, result) + "," + Solution(root.right, map, result);
        //只在第一次重复时加入
        if(map.getOrDefault(serial, 0) == 1){
            result.add(root);
        }
        map.put(serial, map.getOrDefault(serial, 0) + 1);
        return serial;
    }
}




#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#

发布了246 篇原创文章 · 获赞 316 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_20304723/article/details/103039551