EasyTreeDepth-First SearchString MatchingBinary TreeHash Function

Subtree of Another Tree

LeetCode
1 approach, code in all languages

You are given the roots of two binary trees, root and subRoot. Determine whether subRoot appears as a subtree of root.

A subtree consists of some node in root together with all of that node's descendants; it matches subRoot when their structures and node values are identical. Return true if such a matching subtree exists, otherwise false.

Example 1

Input: root = [3,4,5,1,2], subRoot = [4,1,2]

Output: true

The node with value 4 and its two children exactly match subRoot.

Example 2

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

Output: false

The candidate subtree rooted at 4 now has an extra child (0), so it no longer matches subRoot.

Constraints

  • The number of nodes in the root tree is in the range [1, 2000].
  • The number of nodes in the subRoot tree is in the range [1, 1000].
  • -10^4 <= root.val <= 10^4
  • -10^4 <= subRoot.val <= 10^4
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now