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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值