Subtree of Another Tree - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

The recursion starts from the root (main tree) and explores every node to check whether the subTree (subRoot) is identical to any subtree within it. We do this using the main recursive function isSubtree(root, subRoot), which traverses the main tree, and a helper isSameTree(a, b) that checks if two trees are identical.

  1. isSubtree(root, subRoot):
    This function both traverses the main tree and triggers comparison at each node.
    • If root is null, return false — we've reached the end without a match.
    • Check if isSameTree(root, subRoot) returns true — if yes, we found a subtree match.
    • If not, recursively call isSubtree(root.left, subRoot) and isSubtree(root.right, subRoot).

    During this recursion, the main-tree root changes at each step, while the subTree (subRoot) stays constant — since we are trying to find where it matches inside the main tree.

  2. isSameTree(a, b):
    Checks if two trees are identical in structure and node values.
    • If both nulltrue (structures align at leaves).
    • If only one is nullfalse (structure mismatch).
    • If a.val !== b.valfalse (value mismatch).
    • Otherwise → recursively check isSameTree(a.left, b.left) and isSameTree(a.right, b.right).

💡 Why this works

The isSubtree recursion ensures every possible node in the main tree is tested as a potential root for the subtree. The helper isSameTree ensures that a match is only confirmed if both structure and values align perfectly from that point downward.

Time Complexity

O(N × M) — for each of the N nodes in the main tree, we may compare up to M nodes in the subtree during isSameTree checks.

Space Complexity

O(H_N + H_M) auxiliary space — caused by the recursion depth, where H_N and H_M are the heights of the main and sub trees, and N and M are their respective node counts. In the worst case (skewed trees), heights become equal to their sizes.

Visucodize editorial solution titled JS Solution for LeetCode's Subtree of Another Tree coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/subtree-of-another-tree.