-
Notifications
You must be signed in to change notification settings - Fork 0
/
isSubtree.cpp
43 lines (36 loc) · 1.2 KB
/
isSubtree.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
/*
Given two non-empty binary trees s and t,
check whether tree t has exactly the same structure and node values with a subtree of s.
A subtree of s is a tree consists of a node in s and all of this node's descendants.
The tree s could also be considered as a subtree of itself.
*/
#include<iostream>
using namespace std;
// Definition for a binary tree node.
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* s, TreeNode* t) {
if(t == nullptr) return true;
if(s == nullptr) return false;
if(isSameTree(s, t)) return true;
return isSubtree(s->left, t) || isSubtree(s->right, t);
}
bool isSameTree(TreeNode* a, TreeNode* b) {
if(a == nullptr && b == nullptr) return true;
if(a == nullptr || b == nullptr) return false;
return (a->val == b->val) && isSameTree(a->left, b->left) && isSameTree(a->right, b->right);
}
};
int main()
{
Solution s;
return 0;
}