Leetcode 652. Find Duplicate Subtrees 寻找重复子树 解题报告

这道题,给了一个二叉树,然后需要找出所有重复的子树(注意这个子树返回一个就可以了)

做法naive一点可以记录每个node的值,然后比较相同的值的遍历。。
进阶一点的话,可以记录以每个节点为开始时的先序遍历(中左右)的数值,然后遍历的序列如果重复出现了,那么就自然可以加入了

以上问题等价于:
记录每一颗子树的先序/后序便利结果,然后比较看有没有重复的,有重复的就可以加入

PS:后续遍历也可以,只要别让root的顺序在左右之间就好。。

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: 
        1
       / \
      2   3
     /   / \
    4   2   4
       /
      4
The following are two duplicate subtrees:
      2
     /
    4
and
    4
Therefore, you need to return above trees' root in the form of a list.
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def helper(self, root, orders, res):
        if root is None:
            return '#END#'
        # 前序,后续都可以
        my_order = self.helper(root.left, orders, res)+'\t'+self.helper(root.right, orders, res)+"\t"+str(root.val)
        # 只需要返回一个,所以只要再次出现一次就可以了,只返回第一个
        if orders.get(my_order, 0 ) == 1:
            res.append(root)
        orders[my_order] = max(1, orders.get(my_order, 0) + 1)
        return my_order

    def findDuplicateSubtrees(self, root):
        """
        :type root: TreeNode
        :rtype: List[TreeNode]
        """
        orders = dict()
        res = list()
        self.helper(root, orders, res)
        return res

你可能感兴趣的:(leetcode-java)