Subtree of Another Tree

DFS over root; at each node, run an exact-match check against subRoot.

Easy
Time O(m * n) Space O(m + n)
LeetCode
3 min read
tree dfs recursion

Problem#

Return true iff subRoot’s tree is a subtree of root’s tree (same structure and values, rooted somewhere in root).

Examples#

  • root = [3,4,5,1,2], subRoot = [4,1,2]true.
  • root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]false.

Constraints#

  • 1 <= nodes in root <= 2000, 1 <= nodes in subRoot <= 1000.

Approach#

Walk root. At each node, check whether the subtree there is identical to subRoot. Same-tree check is a structural recursion.

Solution#

Subtree of Another Tree
struct TreeNode { int val; TreeNode* left; TreeNode* right; };
class Solution {
bool same(TreeNode* a, TreeNode* b) {
if (!a && !b) return true;
if (!a || !b || a->val != b->val) return false;
return same(a->left, b->left) && same(a->right, b->right);
}
public:
bool isSubtree(TreeNode* root, TreeNode* subRoot) {
if (!root) return false;
if (same(root, subRoot)) return true;
return isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot);
}
};

Editorial#

Naive O(m * n) is fine for the constraints. A faster O(m + n) solution serializes both trees and uses string matching, but it’s overkill here. Short-circuit on the first match.

Complexity#

  • Time: O(m * n).
  • Space: O(m + n) recursion.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.