Find Duplicate Subtrees

Medium Topics Company Tags

Given the root of a binary tree, return all duplicate subtrees.

For each kind of duplicate subtree, you only need to return the root node of any one of them.

Two subtrees are duplicate if they have the same structure with the same node values.

The diagrams below the arrow show the duplicate subtrees found in the tree above.

Example 1:

Find Duplicate Subtrees, example 1: illustration of the example

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

Output: [[2,4],[4]]

Explanation: The subtree rooted at the node with value 2 (with a child 4) appears twice, and the leaf subtree with value 4 also appears a second time as a duplicate, so only one representative of each is returned.

Example 2:

Find Duplicate Subtrees, example 2: illustration of the example

Input: root = [2,1,1]

Output: [[1]]

Explanation: Both leaf children have value 1, forming a duplicate single-node subtree.

Example 3:

Find Duplicate Subtrees, example 3: illustration of the example

Input: root = [2,2,2,3,null,3,null]

Output: [[2,3],[3]]

Explanation: The subtree rooted at the second node with value 2 (with a left child 3) duplicates another subtree, and the leaf subtree with value 3 is duplicated as well.

Constraints:

  • The number of nodes in the tree is in the range [1, 5000].
  • -200 <= Node.val <= 200


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.