Leetcode 652.寻找重复的子树
作者:互联网
寻找重复的子树
给定一棵二叉树,返回所有重复的子树。对于同一类的重复子树,你只需要返回其中任意一棵的根结点即可。
两棵树重复是指它们具有相同的结构以及相同的结点值。
下面是两个重复的子树:
因此,你需要以列表的形式返回上述重复子树的根结点。
思路
Intuition
We can serialize each subtree. For example, the tree
1
/ \
2 3
/ \
4 5
can be represented as the serialization 1,2,#,#,3,4,#,#,5,#,#, which is a unique representation of the tree.
Algorithm
Perform a depth-first search, where the recursive function returns the serialization of the tree. At each node, record the result in a map, and analyze the map after to determine duplicate subtrees.
1 class Solution { 2 Map<String, Integer> count; 3 List<TreeNode> ans; 4 public List<TreeNode> findDuplicateSubtrees(TreeNode root) { 5 count = new HashMap(); 6 ans = new ArrayList(); 7 collect(root); 8 return ans; 9 } 10 11 public String collect(TreeNode node) { 12 if (node == null) return "#"; 13 String serial = node.val + "," + collect(node.left) + "," + collect(node.right); 14 count.put(serial, count.getOrDefault(serial, 0) + 1); 15 if (count.get(serial) == 2) 16 ans.add(node); 17 return serial; 18 } 19 }
标签:node,count,子树,collect,652,ans,serial,Leetcode 来源: https://www.cnblogs.com/kexinxin/p/10383085.html