leetcode - 652. Find Duplicate Subtrees - Java

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]]

思路: 既然是树就要考虑到遍历,其次考虑是前中后哪种遍历,在判断当前节点时要知道我的子节点都长什么样,这就说明是后序遍历,但是我现在只知道我当前节点及其子节点长什么样了,如何知道其他节点及其子节点长什么样呢?我们可以将各个节点及子节点的状态保存在一个map中,进行判断,重复的话就添加到LinkedList中。

public class FindDuplicatSubtrees {
    Map<String,Integer> map = new HashMap<>();
    List<TreeNode> ans = new LinkedList<>();
    public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
        traverse(root);
        return ans;
    }
    public String traverse(TreeNode node){
        if(node == null)return "#";
        String left = traverse(node.left);
        String right = traverse(node.right);
		//将node的左右子树都序列化掉
        String subTree = left + "," + right + "," + node.val;

        int frequent = map.getOrDefault(subTree,0);
        if (frequent == 1){
            ans.add(node);
        }
        map.put(subTree,frequent + 1);
        return subTree;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值