|
| 1 | +/** |
| 2 | + * Definition for a binary tree node. |
| 3 | + * struct TreeNode { |
| 4 | + * int val; |
| 5 | + * TreeNode *left; |
| 6 | + * TreeNode *right; |
| 7 | + * TreeNode() : val(0), left(nullptr), right(nullptr) {} |
| 8 | + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} |
| 9 | + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} |
| 10 | + * }; |
| 11 | + */ |
| 12 | +class Solution { |
| 13 | +public: |
| 14 | + bool isSameTree(TreeNode* p, TreeNode* q) { |
| 15 | + if (p == nullptr && q == nullptr) return true; |
| 16 | + if (p == nullptr || q == nullptr) return false; |
| 17 | + if (p->val != q->val) return false; |
| 18 | + |
| 19 | + return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); |
| 20 | + } |
| 21 | + |
| 22 | + bool isSubtree(TreeNode* root, TreeNode* subRoot) { |
| 23 | + if (root == nullptr) return false; |
| 24 | + if (isSameTree(root, subRoot)) return true; |
| 25 | + return isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot); |
| 26 | + } |
| 27 | + |
| 28 | + // bool ans = false; |
| 29 | + // void check(TreeNode* root, TreeNode* subRoot) { |
| 30 | + // if(root == nullptr || subRoot == nullptr || root->val != subRoot->val) { |
| 31 | + // if(root != nullptr || subRoot != nullptr) |
| 32 | + // ans = false; |
| 33 | + // return; |
| 34 | + // } |
| 35 | + // check(root->left, subRoot->left); |
| 36 | + // check(root->right, subRoot->right); |
| 37 | + // } |
| 38 | + |
| 39 | + // void rec(TreeNode* root, TreeNode* subRoot) { |
| 40 | + // if(root == nullptr || ans) |
| 41 | + // return; |
| 42 | + // if(root->val == subRoot->val) { |
| 43 | + // ans = true; |
| 44 | + // check(root, subRoot); |
| 45 | + // if(ans) return; |
| 46 | + // } |
| 47 | + // rec(root->left, subRoot); |
| 48 | + // rec(root->right, subRoot); |
| 49 | + // } |
| 50 | + |
| 51 | + // bool isSubtree(TreeNode* root, TreeNode* subRoot) { |
| 52 | + // rec(root, subRoot); |
| 53 | + // return ans; |
| 54 | + // } |
| 55 | +}; |
0 commit comments