-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path49_subtree-of-another-tree.cpp
81 lines (66 loc) · 2.4 KB
/
49_subtree-of-another-tree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// DATE: 07-Aug-2023
/* PROGRAM: 49_Tree - Subtree of Another Tree
https://leetcode.com/problems/subtree-of-another-tree/
Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with
the same structure and node values of subRoot and false otherwise.
A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's
descendants. The tree tree could also be considered as a subtree of itself.
Example 1:
Input: root = [3,4,5,1,2], subRoot = [4,1,2]
Output: true
Example 2:
Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
Output: false
*/
// @ankitsamaddar @Aug_2023
#include <iostream>
#include <vector>
using namespace std;
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 isSubtree(TreeNode* root, TreeNode* subRoot) {
if (!subRoot) return true;
if (root == nullptr) return false;
if (sameTree(root, subRoot)) return true;
return isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot);
}
bool sameTree(TreeNode* s, TreeNode* t) {
if (!s or !t) {
return s == t;
}
return s->val == t->val and sameTree(s->left, t->left) and sameTree(s->right, t->right);
}
};
int main() {
TreeNode* root = new TreeNode(3);
root->left = new TreeNode(4);
root->right = new TreeNode(5);
root->left->left = new TreeNode(1);
root->left->right = new TreeNode(2);
root->right->left = nullptr;
root->right->right = nullptr;
root->left->left->left = nullptr;
root->left->left->right = nullptr;
root->left->right->left = nullptr;
root->left->right->right = nullptr;
// subRoot
TreeNode* subRoot = new TreeNode(4);
subRoot->left = new TreeNode(1);
subRoot->right = new TreeNode(2);
subRoot->left->left = nullptr;
subRoot->left->right = nullptr;
subRoot->right->left = nullptr;
subRoot->right->right = nullptr;
Solution sol;
bool res = sol.isSubtree(root, subRoot);
cout << boolalpha << res << endl;
return 0;
}