Given the root of 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 the same node values.
Example 1:

Input: root = [1,2,3,4,null,2,4,null,null,4] Output: [[2,4],[4]]
Example 2:

Input: root = [2,1,1] Output: [[1]]
Example 3:

Input: root = [2,2,2,3,null,3,null] Output: [[2,3],[3]]
Constraints:
- The number of the nodes in the tree will be in the range
[1, 10^4] -200 <= Node.val <= 200
----------------------------------
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findDuplicateSubtrees(self, root: TreeNode) -> List[TreeNode]:
dic,res = {},[]
def dfs(root):
nonlocal dic,res
if (root == None):
return ""
lstr = dfs(root.left)
rstr = dfs(root.right)
total = "{0}-{1}-{2}".format(root.val,lstr,rstr)
if (total in dic):
if dic[total] != None: #bug1: add only once
res.append(root)
dic[total] = None
else:
dic[total] = root
return total
dfs(root)
return res

本文介绍了一种查找二叉树中所有重复子树的方法,并通过示例详细解释了算法的具体实现过程。对于每种类型的重复子树,仅需返回其中一个根节点。

被折叠的 条评论
为什么被折叠?



