[LeetCode] Subtree of Another Tree

572. 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.

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
/**
* 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 {
bool eq(TreeNode* o, TreeNode* t) {
if(!o)
return !t;
if(!t)
return !o;
if(o->val != t->val)
return false;
if(!eq(o->left, t->left))
return false;
return eq(o->right, t->right);
}
public:
bool isSubtree(TreeNode* root, TreeNode* subRoot) {
vector<TreeNode*> cand;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()) {
auto node = q.front(); q.pop();
if(node->val == subRoot->val)
cand.push_back(node);
if(node->left)
q.push(node->left);
if(node->right)
q.push(node->right);
}
for(auto c : cand)
if(eq(c,subRoot))
return true;
return false;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/28/PS/LeetCode/subtree-of-another-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.