</>

572. Subtree of Another Tree

Easy NeetCode 150
Trees Time O(N*M) Space O(H)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Trees
Time
O(N*M)
Space
O(H)

Standard Solution (C++)

SummaryGiven two binary trees, determine whether the second tree (`subRoot`) appears as an exact structural and value match rooted at some node within the first tree (`root`). Return true if such a matching subtree exists, false otherwise.

Approach
  • Perform a DFS traversal over every node in root; at each node, check whether the subtree rooted there is identical to subRoot.
  • The identity check (isSameTree) simultaneously walks both trees, returning true only when both are null, and false if one is null or the values differ.
  • This cleanly separates two concerns — "where to look" (traversal of the main tree) and "what to match" (pairwise equality) — making the logic easy to reason about.
  • The short-circuit in isSubtree ensures we stop as soon as a match is found.
#include <cstddef>
using namespace std;

// TreeNode definition (provided by LeetCode judge)
struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right)
        : val(x), left(left), right(right) {}
};

class Solution {
    // Returns true if the two trees are structurally identical with equal values.
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if (!p && !q) return true;           // both exhausted simultaneously
        if (!p || !q) return false;          // one ran out before the other
        if (p->val != q->val) return false;  // value mismatch
        return isSameTree(p->left,  q->left)
            && isSameTree(p->right, q->right);
    }

public:
    bool isSubtree(TreeNode* root, TreeNode* subRoot) {
        // A null main tree cannot contain any non-trivial subtree.
        if (!root) return false;

        // Check the current node, then recurse into left and right children.
        return isSameTree(root, subRoot)
            || isSubtree(root->left,  subRoot)
            || isSubtree(root->right, subRoot);
    }
};
Time O(N * M) where N is the number of nodes in root and M is the number of nodes in subRoot — each of the N nodes can trigger an O(M) identity check. Space O(H) where H is the height of root (recursion stack depth); O(N) in the worst case for a skewed tree, O(log N) for a balanced tree.

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode() : val(0), left(nullptr), right(nullptr) {}
*     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
*     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
    bool isIdentical(TreeNode* root, TreeNode* subRoot){
        if(!root && !subRoot){
            return true;
        }
        if(!root || !subRoot || root->val != subRoot->val){
            return false;
        }
        return isIdentical(root->left, subRoot->left) && isIdentical(root->right, subRoot->right);
    }
    bool isSubtree(TreeNode* root, TreeNode* subRoot) {
        return isIdentical(root, subRoot) || (root && (isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot)));
    }
};

// Time Complexity: O(N*M)
// Space Complexity: O(H) where H is the height of the tree, since we are using recursion (the call stack will take up space). 
// In the worst case (skewed tree), H = N. In the best case (balanced tree), H = log(N).
// We can use preorder traversal and serialize the tree to a string, then check if the subtree is a substring of the string, this will be O(N+M) time complexity.
Time O(N*M) Space O(H)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern