LeetCode 0652. Find Duplicate Subtrees Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0652. Find Duplicate Subtrees

Description

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, 5000]
  • -200 <= Node.val <= 200

Solutions

Solution 1

PythonJavaC++GoTypeScriptRust
# 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: Optional[TreeNode] ) -> List[Optional[TreeNode]]: def dfs(root): if root is None: return '#' v = f'{root.val},{dfs(root.left)},{dfs(root.right)}' counter[v] += 1 if counter[v] == 2: ans.append(root) return v ans = [] counter = Counter() dfs(root) return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !