Algorithm Puzzles: Subtree of Another Tree

Algorithm Puzzles everyday every week sometimes: Subtree of Another Tree

Puzzle

Puzzle from leetcode:

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.

Solution

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
class Solution {
public:
bool isSubtree(const TreeNode* root, const TreeNode* subRoot) const {
if (!bfs(root, subRoot)) {
if (root->left != nullptr) {
if (isSubtree(root->left, subRoot)) {
return true;
}
}
if (root->right != nullptr) {
if (isSubtree(root->right, subRoot)) {
return true;
}
}
} else {
return true;
}

return false;
}

private:
bool bfs(const TreeNode* root, const TreeNode* subRoot) const {
if (subRoot == nullptr && root == nullptr) {
return true;
}

if (root == nullptr || subRoot == nullptr) {
return false;
}

if (root->val == subRoot->val) {
if (!bfs(root->left, subRoot->left)) {
return false;
}
if (!bfs(root->right, subRoot->right)) {
return false;
}
} else {
return false;
}

return true;
}
};

T.C.: O(M*N)