652. Find Duplicate Subtrees

网友投稿 227 2022-12-01

652. Find Duplicate Subtrees

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.

Example 1:

\ 2 3 / / \

The following are two duplicate subtrees:

2 / 4

and

4

Therefore, you need to return above trees’ root in the form of a list.

思路: Intuition

We can serialize each subtree. For example, the tree

\ 2 3 / \

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.

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */class Solution { Map count; List ans; public List 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

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java实现红黑树(平衡二叉树)的详细过程
下一篇:662. Maximum Width of Binary Tree
相关文章

 发表评论

暂时没有评论,来抢沙发吧~