Leetcode-652 寻找重复的子树

作者: itbird01 | 来源:发表于2021-10-22 00:14 被阅读0次

    652. 寻找重复的子树

    解题思路

    1.将遍历到的数据塞入map中,key为node的序列字符串(1,2,#,#,3,4,#,#,5,#,#),value为出现的次数
    2.将出现次数大于1的node,作为结果ans一员

    解题遇到的问题

    1.map存储中,需要设计合理的键,此题用Node作为key,发现不可行,因为没有直接的方法对比两个node结构相同,所以key设计为node的序列之后的字符串

    后续需要总结学习的知识点

    1.二叉树的遍历,还是需要深入学习、总结一下实践和具体的设计思想,而不是单单会写代码

    ##解法1
    class Solution {
        Map<String, Integer> count;
        List<TreeNode> ans;
        public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
            count = new HashMap();
            ans = new ArrayList();
            collect(root);
            return ans;
        }
    
        public String collect(TreeNode node) {
            if (node == null) return "#";
            String serial = node.val + "," + collect(node.left) + "," + collect(node.right);
            count.put(serial, count.getOrDefault(serial, 0) + 1);
            if (count.get(serial) == 2)
                ans.add(node);
            return serial;
        }
    }
    

    相关文章

      网友评论

        本文标题:Leetcode-652 寻找重复的子树

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