题目链接:
https://leetcode.cn/problems/shu-de-zi-jie-gou-lcof/description/?favorite=xb9nqhhg&orderBy=hot
代码:
/**
* 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:
int flag=0;
int ff=1;
void check(TreeNode *A,TreeNode *B)
{
if(ff==0) return ;
if((A->val!=B->val)|| (A->left==NULL && B->left!=NULL) || (A->right==NULL && B->right!=NULL))
{
ff=0;
return ;
}
if(A->left!=NULL&&B->left!=NULL)
{
check(A->left,B->left);
}
if(A->right!=NULL&&B->right!=NULL)
{
check(A->right,B->right);
}
if((A->right!=NULL&&B->right==NULL)||(A->left!=NULL&&B->left==NULL))
{
return ;
}
}
void panduan(TreeNode *A,TreeNode *B)
{
if(A==NULL) return ;
if(A->val==B->val)
{
printf("%d\n",A->val);
ff=1;
check(A,B);
if(ff==1)
{
flag =1;
}
}
if(A->right!=NULL)
{
panduan(A->right,B);
}
if(A->left!=NULL) panduan(A->left,B);
}
bool isSubStructure(TreeNode* A, TreeNode* B) {
if(B==NULL) return false;
panduan(A,B);
if(flag) return true;
else return false;
}
};