Skip to main content

Subtree of Another Tree

Return true if subRoot is a subtree of root Example: [3,4,5,1,2], [4,1,2] => True

Subtree of Another Tree rewards clean traversal structure more than any clever shortcut. It's a great warm-up that builds traversal modeling without a ton of moving parts. Once your traversal structure is solid, you can reuse it across dozens of problems.

StringTreesBFS / DFSMath & Geometry

Examples

You write

is_subtree(root: Optional[TreeNode], sub_root: Optional[TreeNode])

  1. Example 1

    Input
    root = [3,4,5,1,2], subRoot = [4,1,2]
    returns
    true
  2. Example 2

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

The pattern behind it

Strings

I reach for it when

  • The input is text and the answer is a count, a substring or a new string.
  • You need to compare, reverse or rebuild characters.

Say this before you type. Say which array pattern the string is hiding before you touch a character.

All 51 Strings problems

Trees

I reach for it when

  • Each node has children, and the answer depends on the subtrees.
  • The statement says depth, height, ancestor or path.

Say this before you type. Say what a call returns for an empty tree, and what it returns for a node.

All 22 Trees problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Subtree of Another Treeeasy