Skip to problem
←

Subtree of Another Tree

Easy 0 attempts

Given two nonempty binary trees root and subRoot, determine whether subRoot is a subtree of root.

Choose any node of root and include all of its descendants. This entire tree must match subRoot in both values and structure, including which children are missing. You cannot omit extra branches or swap left and right children.

The whole tree may be its own subtree. Repeated values are allowed, so matching one node's value is not sufficient.

Function contract

Implement isSubtree(root, subRoot). Trees use level-order arrays with null for missing children. The editor passes nodes with val, left, and right properties; [] becomes null.

Output: Return true if a node in root, together with all its descendants, exactly matches subRoot in values and left/right structure; otherwise return false.

Example 1

Input
root = [3,4,5,1,2]
subRoot = [4,1,2]
Output
true

Example 2

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

Explanation: The node with value 4 has an additional descendant 0 below its right child. A subtree includes every descendant, so that branch cannot be ignored.

Constraints
  • Each of root and subRoot contains between 1 and 2000 nodes
  • -10^4 <= Node.val <= 10^4

Search and Compare Trees

Visit every possible subtree root. At each candidate, compare pairs of nodes: values must match, and both corresponding children must either exist or be absent. Stop that comparison on the first mismatch.

Explicit stacks avoid relying on JavaScript's recursion limit for skewed trees. Null child pairs are included so different shapes cannot compare equal.

javascript
function isSubtree(root, subRoot) {
  function sameTree(a, b) {
    const pairs = [[a, b]];
    while (pairs.length) {
      const [left, right] = pairs.pop();
      if (!left && !right) continue;
      if (!left || !right || left.val !== right.val) return false;
      pairs.push([left.left, right.left], [left.right, right.right]);
    }
    return true;
  }

  const candidates = [root];
  while (candidates.length) {
    const node = candidates.pop();
    if (sameTree(node, subRoot)) return true;
    if (node.left) candidates.push(node.left);
    if (node.right) candidates.push(node.right);
  }
  return false;
}

Time: O(m × n) in the worst case, where m and n are the two node counts.

Auxiliary space: O(h₁ + h₂) for the traversal and comparison stacks, bounded by the heights of the two trees.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript