Skip to the code
cf.
+25 XP

#364 Repeated Component Subtrees

medium

A design-system audit looks for repeated pieces of UI that could become shared components. The page is a binary tree of component ids. Two subtrees are duplicates when they have the same shape and the same id in every position.

Write countRepeatedShapes(root) that returns how many different subtree shapes appear two or more times in the tree. Each shape counts once, however often it repeats. A subtree is a node with everything below it.

Example 1

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

The subtree 2 → 4 appears twice, and the leaf 4 appears three times.

Example 2

Input: root = [2,1,1]
Output: 1

The leaf 1 appears twice.

Constraints

  • 0 <= number of nodes <= 5000
  • -200 <= id <= 200

Trees are written level by level, like [1, 2, 3, null, 4], where null is a missing child. Your function works with TreeNode objects, each with val, left, and right.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).