原题
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.
解法1
前序遍历+字典. 定义字典seen保存已见过的子树, 我们遍历二叉树, 用’#'代表空节点, 将每个节点对应的二叉树以字符串的形式存入字典, 如果seen中已经见过该二叉树, 则将节点加到res里, 这里注意当seen[string] == 1时才能往结果里加, 因为我们的结果不能有重复的节点.
代码
# 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 findDuplicateSubtrees(self, root):
"""
:type root: TreeNode
:rtype: List[TreeNode]
"""
# pre-order
def traverse(root):
if not root:
return '#'
string = str(root.val) + traverse(root.left) + traverse(root.right)
if string in seen and seen[string] == 1:
res.append(root)
seen[string] += 1
return string
res = []
seen = collections.defaultdict(int)
traverse(root)
return res
解法2
后序遍历+字典. 思路与解法1相同, 我们从叶子节点往根节点读取二叉树.
代码
# 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 findDuplicateSubtrees(self, root):
"""
:type root: TreeNode
:rtype: List[TreeNode]
"""
# post-order
def traverse(root):
if not root:
return '#'
string = traverse(root.left) + traverse(root.right) + str(root.val)
if string in seen and seen[string] == 1:
res.append(root)
seen[string] += 1
return string
res = []
seen = collections.defaultdict(int)
traverse(root)
return res
本文深入探讨了在二叉树中查找所有重复子树的算法。提供了两种解决方案:前序遍历+字典和后序遍历+字典的方法。通过使用字符串表示法和字典来跟踪和识别重复的子树结构。
1360

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



