Subtree of Another Tree

Easy Trees & BST Traversals

Subtree of Another Tree is a easy trees & bst problem solved with the traversals pattern. The best approach, serialize both trees, then kmp, runs in O(m + n) time and O(m + n) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from compare at every node up.

Problem

You are given the roots of two binary trees, root and subRoot. Return true if some node of root is the top of a subtree that is identical to subRoot: the same shape and the same value in every position. Otherwise return false.

The subtree at a node is that node together with all of its descendants. So a node whose children match subRoot but which has extra nodes further down does not count. The whole of root is also one of its own subtrees.

Examples

Example 1

Input
root = [5, 3, 8, 1, 4], subRoot = [3, 1, 4]
Output
true
Why
The node 3 in root has children 1 and 4 and nothing below them, which is exactly subRoot.

Example 2

Input
root = [5, 3, 8, 1, 4, null, null, null, null, 2], subRoot = [3, 1, 4]
Output
false
Why
Node 3 still has children 1 and 4, but 4 now has a child 2. A subtree takes every descendant, so the subtree at 3 has four nodes and does not equal subRoot.

Example 3

Input
root = [2, 2, null, 2], subRoot = [2, 2]
Output
true
Why
Root is a chain of three 2s going left. The subtree at the middle node is a 2 with a left child 2, which matches subRoot. The subtree at the top has one node too many.

Constraints

  • root has 1 to 2000 nodes.
  • subRoot has 1 to 1000 nodes.
  • -10^4 <= Node.val <= 10^4

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 57 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Compare at every nodeO(m * n)O(h)
Serialize both trees, then KMPO(m + n)O(m + n)

1Compare at every node

TimeO(m * n)Each of the m nodes of root can start a comparison that walks up to n nodes of subRoot.
SpaceO(h)Only the recursion stack, as deep as the height of root.

A copy of subRoot, if it exists, starts at some node of root. Visit every node of root and run the same-tree check from there; stop at the first success.

  1. If root is null, there is nowhere left to look: return false.
  2. If the tree at root is identical to subRoot, return true.
  3. Otherwise look in the left subtree, then in the right subtree.
  4. isSame(a, b): if either is null, they are equal only if both are; else the values must match and both pairs of children must be the same.
class Solution {
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if (root == null) return false;
        if (isSame(root, subRoot)) return true;
        return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
    }

    private boolean isSame(TreeNode a, TreeNode b) {
        if (a == null || b == null) return a == b;
        return a.val == b.val && isSame(a.left, b.left) && isSame(a.right, b.right);
    }
}

2Serialize both trees, then KMP

TimeO(m + n)Serializing visits each node once, and KMP never moves backwards in the text, so both phases are linear in the sequence lengths (2m + 1 and 2n + 1 tokens).
SpaceO(m + n)The two token sequences and the failure table, plus the recursion stack while serializing.

Write each tree as its preorder sequence of values, with a special NULL token for every missing child. These sequences describe a tree exactly, and the sequence of any subtree of root is a contiguous block of root's sequence. So subRoot is a subtree exactly when its sequence appears inside root's sequence, which KMP finds in linear time. Working with whole tokens, not characters, keeps 2 from matching inside 12.

  1. Serialize: at null, append NULL; otherwise append the value, then serialize the left child, then the right child.
  2. Build the KMP failure table of the pattern (subRoot's sequence): fail[i] is the length of the longest proper prefix of pat[0..i] that is also a suffix of it.
  3. Scan the text (root's sequence) with a matched length k: while the next token differs and k > 0, fall back to fail[k - 1]; if it matches, k++.
  4. If k reaches the pattern length, return true. If the scan ends first, return false.
class Solution {
    private static final int NULL = Integer.MIN_VALUE;

    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        List<Integer> text = new ArrayList<>(), pat = new ArrayList<>();
        serialize(root, text);
        serialize(subRoot, pat);
        int m = pat.size();
        int[] fail = new int[m];
        for (int i = 1, k = 0; i < m; i++) {
            while (k > 0 && !pat.get(i).equals(pat.get(k))) k = fail[k - 1];
            if (pat.get(i).equals(pat.get(k))) k++;
            fail[i] = k;
        }
        for (int i = 0, k = 0; i < text.size(); i++) {
            while (k > 0 && !text.get(i).equals(pat.get(k))) k = fail[k - 1];
            if (text.get(i).equals(pat.get(k))) k++;
            if (k == m) return true;
        }
        return false;
    }

    private void serialize(TreeNode node, List<Integer> out) {
        if (node == null) {
            out.add(NULL);
            return;
        }
        out.add(node.val);
        serialize(node.left, out);
        serialize(node.right, out);
    }
}

Edge cases to test

  • subRoot equals the whole of root
  • subRoot is a single node that matches a leaf
  • A node matches subRoot at the top but has an extra descendant further down
  • Same values but a left child where subRoot has a right child
  • Many nodes share subRoot's root value, so a match is only found deep in the tree
  • Values whose digits overlap, like 2 and 12 (a string-based method must keep tokens apart)

Hints

Hint 1

You already know how to check whether two trees are identical. Where in root could a copy of subRoot start?

Hint 2

Trying every node of root as the start works, but can cost one full comparison per node. Can you turn each tree into a sequence so that a subtree becomes a contiguous block?

Hint 3

A preorder listing that also writes a marker for every missing child describes a tree exactly, and the listing of any subtree is a contiguous piece of the whole listing. Now it is a pattern search: use KMP.

FAQ

What is the best time complexity for Subtree of Another Tree?

Serialize both trees, then KMP runs in O(m + n) time and O(m + n) extra space. Serializing visits each node once, and KMP never moves backwards in the text, so both phases are linear in the sequence lengths (2m + 1 and 2n + 1 tokens).

Which pattern does Subtree of Another Tree use?

It is a trees & bst problem that uses the traversals pattern. Other problems with the same pattern: Binary Tree Level Order Traversal, Binary Tree Zigzag Level Order Traversal, Binary Tree Level Order Traversal II.

Is there a brute force solution for Subtree of Another Tree?

Yes. Compare at every node takes O(m * n) time and O(h) space. A copy of subRoot, if it exists, starts at some node of root.

Which edge cases should I test for Subtree of Another Tree?

subRoot equals the whole of root; subRoot is a single node that matches a leaf; A node matches subRoot at the top but has an extra descendant further down; Same values but a left child where subRoot has a right child; Many nodes share subRoot's root value, so a match is only found deep in the tree; Values whose digits overlap, like 2 and 12 (a string-based method must keep tokens apart).