1. Recursive Tree Equality Check
Intuition
Define isSame(a, b). In isSubtree(root, subRoot), if isSame(root, subRoot) is true return true; otherwise recurse on left and right.
When to apply: Standard intuitive solution.
Algorithm
- Step 1: If root == null return false.
- Step 2: If isSame(root, subRoot) return true.
- Step 3: Return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot).
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution { bool isSame(TreeNode* a, TreeNode* b) { if (!a && !b) return true; if (!a || !b) return false; return a->val == b->val && isSame(a->left, b->left) && isSame(a->right, b->right); }public: bool isSubtree(TreeNode* root, TreeNode* subRoot) { if (!root) return false; if (isSame(root, subRoot)) return true; return isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot); }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n * m)— Worst-case checks all m nodes of subRoot at each of the n nodes of root. - Space complexity:
O(h)— Call stack depth bounded by tree height h.