Steward
分享是一種喜悅、更是一種幸福
程式語言 - LeetCode - C++ - 572. Subtree of Another Tree
題目:

解答:
/**
* 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 is_same(TreeNode *a, TreeNode *b) {
if (!a && !b) {
return true;
}
if (!a || !b) {
return false;
}
if (a->val != b->val) {
return false;
}
return is_same(a->left, b ->left) && is_same(a->right, b->right);
}
bool isSubtree(TreeNode* root, TreeNode* subRoot) {
if (!root) {
return false;
}
if (is_same(root, subRoot)) {
return true;
}
return isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot);
}
};