22 · Tree Recursion

#572 Subtree of Another Tree

Easysolve on LeetCode ↗

frequently reported atMetaAmazonGoogleMicrosoft

the problem

In plain words

You get two trees, root and subRoot. Return true if some node of root, together with everything below it, is an exact copy of subRoot — same shape, same values. root itself counts as one of its own subtrees.

in root = [3,4,5,1,2], subRoot = [4,1,2]

out true

Node 4 with children 1 and 2 is an exact copy.

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

out false

Node 4 looks right at first, but its child 2 has an extra child 0 — a subtree takes everything below it.

  • 1 ≤ nodes in root ≤ 2000
  • 1 ≤ nodes in subRoot ≤ 1000
  • -10⁴ ≤ Node.val ≤ 10⁴

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #100
      Same Tree
      Easyin Tree Recursion
    2. #101
      Symmetric Tree
      Easyin Tree Recursion
    3. #297