Subtree of Another Tree

EasyTrees

Given the roots of two binary trees, root and subRoot, return true if some node of root, together with everything below it, is the same tree as subRoot, and false otherwise. The whole of root counts too.

Same means the same shape with the same values: the node you pick must have nothing below it that subRoot lacks.

On this page a tree is written in level order, top to bottom and left to right, with null where a child is missing: [6, 3, 8, 1] is 6 with children 3 and 8, and 3 with a left child 1.

Examples

Example 1
Input:  root = [8, 2, 5, null, 6, 3, 1], subRoot = [5, 3, 1]
Output: true

The node 5, with its children 3 and 1, is exactly subRoot.

Example 2
Input:  root = [6, 2, 8, 1, 3], subRoot = [2, 1]
Output: false

The node 2 has children 1 and 3, and subRoot has no 3, so the tree under 2 is not the same.

Constraints

  • root has 1 to 2000 nodes, and subRoot has 1 to 1000.
  • -10⁴ ≤ node.val ≤ 10⁴

Stuck?

Hint 1

Every node of root is a place subRoot could start. At each one, ask whether the tree hanging from it is the same as subRoot.

Hint 2

Write a helper that tells whether two trees are the same, and call it at every node as you walk root. When a value matches but the trees differ, keep walking: a later node may still match.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 11 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur