Leetcode 652 Solution
This article provides solution to leetcode question 652 (find-duplicate-subtrees)
Access this page by simply typing in "lcs 652" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/find-duplicate-subtrees
Solution
# 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 dfs(self, root):
if root == None:
return "#"
res = "{},{},{}".format(
root.val,
self.dfs(root.left),
self.dfs(root.right),
)
if res not in self.cache:
self.cache[res] = root
else:
if self.cache[res] is not None:
self.ans.append(root)
self.cache[res] = None
return res
def findDuplicateSubtrees(self, root):
"""
:type root: TreeNode
:rtype: List[TreeNode]
"""
self.cache = {}
self.ans = []
self.dfs(root)
return self.ans