要求:b树是不是a树一部分
思路:有个坑就是遍历时候b没了,a还可以有。跟572. 另一棵树的子树一样
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* first=nullptr;
bool ans=false;
void findfirst(TreeNode* A,TreeNode* B){
if(!A)return;
if(A->val==B->val){
first=A;
ans=ans||compare(first,B);
}
findfirst(A->left,B);
findfirst(A->right,B);
}
bool compare(TreeNode* A,TreeNode* B){
if(!B)return true;
if(!A&&B)return false;
if(A->val!=B->val)return false;
return compare(A->left,B->left)&&compare(A->right,B->right);
}
bool isSubStructure(TreeNode* A, TreeNode* B) {
if(!B)return false;
findfirst(A,B);
return ans;
}
};