|
| 1 | +/* |
| 2 | + * Problem: 572 |
| 3 | + * Name: Subtree Of Another Tree |
| 4 | + * Difficulty: Easy |
| 5 | + * Topic: Binary Trees |
| 6 | + * Link: https://leetcode.com/problems/subtree-of-another-tree/ |
| 7 | + */ |
| 8 | + |
| 9 | +#include <bits/stdc++.h> |
| 10 | +using namespace std; |
| 11 | + |
| 12 | +// Tree Node Implementation |
| 13 | +struct TreeNode { |
| 14 | + int val; |
| 15 | + TreeNode *left; |
| 16 | + TreeNode *right; |
| 17 | + TreeNode() : val(0), left(nullptr), right(nullptr) {} |
| 18 | + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} |
| 19 | + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} |
| 20 | +}; |
| 21 | + |
| 22 | +// Recursive Approach |
| 23 | +// Time Complexity: O(n²) |
| 24 | +// Space Complexity: O(1) |
| 25 | +bool isSameTree(TreeNode* p, TreeNode* q); |
| 26 | +bool isSubtree(TreeNode* root, TreeNode* subRoot) { |
| 27 | + if (root == subRoot) {return true;} |
| 28 | + if (root == nullptr || subRoot == nullptr) {return false;} |
| 29 | + return isSameTree(root, subRoot) || |
| 30 | + isSubtree(root->left, subRoot) || |
| 31 | + isSubtree(root->right, subRoot); |
| 32 | +} |
| 33 | +// Auxiliar function from problem "SameTree" |
| 34 | +bool isSameTree(TreeNode* p, TreeNode* q) { |
| 35 | + if (p == q){ return true;} |
| 36 | + else if (p == NULL || q == NULL){ return false;} |
| 37 | + else if (p->val != q->val) {return false;} |
| 38 | + return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); |
| 39 | +} |
0 commit comments