Leetcode 652 Find Duplicate Subtrees

本文介绍了一种用于查找二叉树中所有重复子树的方法。通过序列化节点并使用哈希映射来跟踪每个子树出现的次数,该算法能够有效地识别出所有重复的子树结构。提供两种实现方式:一种直接比较序列化的字符串;另一种则为每个唯一子树分配ID进行跟踪。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem:

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.

Analysis:

  1. Store all the nodes into an ArrayList. And compare each pair
  2. serilize each node with the form:
    series = (root.val, < encoder root.left >, < encoder root.right >)
    In this way, each different node will have a unique series String
  3. set ID number for each TreeNode
    we can use map.computeIfAbsent

Some basic knowledge

map.computeIfAbsent:
Object key = map.get(“key”);
if (key == null) {
key = new Object();
map.put(“key”, key);
}

// the above code is the same as:
Object key2 = map.computeIfAbsent(“key”, k -> new Object());

public class Solution1 {
	// method 2
	public List<TreeNode> findDuplicateSubtrees(TreeNode root){
		
		HashMap<String, Integer> counter = new HashMap<>();
		List<TreeNode> nodes = new ArrayList<TreeNode>();
		
		serilization(counter, nodes, root);
		return nodes;
	}
	
	public String serilization(HashMap<String, Integer> counter, List<TreeNode> nodes, TreeNode root){
		
		if (root == null) return "";
		String series = "(" + root.val + "," + serilization(counter, nodes, root.left) + "," + serilization(counter, nodes, root.right) + ")";
		counter.put(series, counter.getOrDefault(series, 0) + 1);
		if (counter.get(series) == 2) {
			nodes.add(root);
		}
		return series;
	}
	
	
	
	// method 3
	int t = 1;
	public List<TreeNode> findDuplicateSubtrees1(TreeNode root){
		
		
		HashMap<String, Integer> IDs = new HashMap<>();
		HashMap<Integer, Integer> counter = new HashMap<>();
		List<TreeNode> res = new ArrayList<>();
		
		setID(IDs, counter, res, root);
		
		return res;	
	}
	
	public int setID(HashMap<String, Integer> IDs, HashMap<Integer, Integer> counter, List<TreeNode> res,  TreeNode root){
		
		if (root == null) return 0;
		int leftNum = setID(IDs, counter, res,  root.left);
		int rightNum = setID(IDs, counter, res,  root.right);
		
		String nodeExpre = "(" + root.val + "," + leftNum + "," + rightNum + ")";
		int ID = IDs.computeIfAbsent(nodeExpre, x -> t++);
		counter.put(ID, counter.getOrDefault(ID, 0)+1);
		if (counter.get(ID) == 2) {
			res.add(root);
		}
		return ID;
		
	}	
	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值