forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0572-subtree-of-another-tree.cpp
45 lines (42 loc) · 1.27 KB
/
0572-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
/*
Given the roots of 2 binary trees, return true if a tree has a subtree of the other tree
Check at each node of the root tree if it's the same as the subRoot tree (structure + values)
Time: O(m x n)
Space: O(m)
*/
/**
* 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* root, TreeNode* subRoot) {
if (root == NULL) {
return false;
}
if (isSame(root, subRoot)) {
return true;
}
return isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot);
}
private:
bool isSame(TreeNode* root, TreeNode* subRoot) {
if (root == NULL && subRoot == NULL) {
return true;
}
if (root == NULL || subRoot == NULL) {
return false;
}
if (root->val != subRoot->val) {
return false;
}
return isSame(root->left, subRoot->left) && isSame(root->right, subRoot->right);
}
};