LeetCode 652. Find Duplicate Subtrees
考点 | 难度 |
---|---|
DFS | Medium |
题目
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.
思路
用dictionary储存root - left - right as strings,返回所有出现次数大于1的string
顺序的解释:
答案
class Solution:
def findDuplicateSubtrees(self, root):
def trv(root):
if not root: return "null"
struct = "%s,%s,%s" % (str(root.val), trv(root.left), trv(root.right))
nodes[struct].append(root)
return struct
nodes = collections.defaultdict(list)
trv(root)
return [nodes[struct][0] for struct in nodes if len(nodes[struct]) > 1]