Blind 75
28 / 75Free practice

Subtree of Another Tree

Easy · Trees

Jump to code

Determine whether a nonempty binary tree subRoot appears as an entire subtree of root, with exactly the same node values and null-child structure.

Examples

Example 1

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

Output: true

Example 2

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

Output: false

Constraints

  • 1 <= The number of nodes in both trees <= 100
  • -100 <= root.val, subRoot.val <= 100

Function contract

Trees use level-order arrays, with null for a missing child. Your code receives TreeNode objects with val, left, and right fields.

Need a hint?

At each candidate root, use the same-tree comparison.

Real tree interview questions

Questions on the same topic that candidates reported from real company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 7 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    3,
    4,
    5,
    1,
    2
  ],
  [
    4,
    1,
    2
  ]
]
Expected
true
Case 2
Input
[
  [
    3,
    4,
    5,
    1,
    2,
    null,
    null,
    null,
    null,
    0
  ],
  [
    4,
    1,
    2
  ]
]
Expected
false
Case 3
Input
[
  [
    1
  ],
  [
    1
  ]
]
Expected
true
Case 4
Input
[
  [
    1,
    2,
    3
  ],
  [
    2
  ]
]
Expected
true
Case 5
Input
[
  [
    1,
    2,
    3
  ],
  [
    4
  ]
]
Expected
false

Drafts are saved per language in this browser when storage is available.