-
Notifications
You must be signed in to change notification settings - Fork 11
/
Day-115.cpp
45 lines (41 loc) · 1.2 KB
/
Day-115.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
//
// Created by Amit Kumar on 20/03/23.
//
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 {
bool isExactTreeMatch(TreeNode*p, TreeNode*q) {
// copy and replace content of "isSameTree" with this code to get a solution for leetcode.
if (p == nullptr && q == nullptr) {
return true;
} else if (p == nullptr or q == nullptr) {
return false;
}
if (p -> val != q->val) {
return false;
}
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
public:
// using below function as helper method as checker for subtree matching.
bool isSameTree(TreeNode *p, TreeNode *q) {
if (isExactTreeMatch(p,q)) {
return true;
}
// check right subtree.
if (q->left && isSameTree(p, q->left)) {
return true;
}
// check left subtree
if (q->right && isSameTree(p, q->right)) {
return true;
}
return false;
}
};