EasyTreeDepth-First SearchString MatchingBinary TreeHash Function

1 approach, code in every language

Problem description

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

After the pattern

Now solve one you haven't seen.

Does the Rig Hold This Section is our own problem on the technique behind Subtree of Another Tree: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free