1. Pairwise Tree Comparison for Every Subtree
Intuition
Traverse tree to collect all n subtree root pointers. For every pair (i, j), check if isSameTree(i, j) is true. Collect unique matching subtrees.
When to apply: Basic baseline check.
Algorithm
- Step 1: Collect all subtree root nodes into an array nodes.
- Step 2: Compare each pair (nodes[i], nodes[j]) using isSameTree.
- Step 3: Deduplicate identical subtree structures.
- Step 4: Return collected unique roots.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: 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); } void collect(TreeNode* node, vector<TreeNode*>& nodes) { if (!node) return; nodes.push_back(node); collect(node->left, nodes); collect(node->right, nodes); } vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) { vector<TreeNode*> nodes; collect(root, nodes); vector<TreeNode*> res; vector<bool> used(nodes.size(), false); for (int i = 0; i < nodes.size(); ++i) { if (used[i]) continue; bool duplicateFound = false; for (int j = i + 1; j < nodes.size(); ++j) { if (!used[j] && isSame(nodes[i], nodes[j])) { used[j] = true; duplicateFound = true; } } if (duplicateFound) res.push_back(nodes[i]); } return res; }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n^3)— There are O(n2) pairs, and isSameTree takes O(n) per pair. - Space complexity:
O(n)— List of subtree pointers.