题目链接https://leetcode-cn.com/problems/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 isSubtree(TreeNode* s, TreeNode* t) {
if(t==NULL){//空树是任何树的子树
return true;
}else{
if(s==NULL){//s不能为空树
return false;
}else{
if(s->val == t->val){//在s中找与t的根相同值的节点,查看该节点的子树是否与t完全相同
bool flag = isSameTree(s->left, t->left) && isSameTree(s->right, t->right);
if(flag==true){//找到了s中与t完全相同的子树
return true;
}
}
return isSubtree(s->left, t) || isSubtree(s->right, t);//在s中寻找新的与t的根相同值的节点
}
}
return false;
}
bool isSameTree(TreeNode* s, TreeNode* t){
if(s==NULL && t==NULL){//都为空
return true;
}else if(s==NULL || t==NULL){//其中一个为空,另一个不为空
return false;
}else{//都不是空树
if(s->val == t->val){
return isSameTree(s->left, t->left) && isSameTree(s->right, t->right);
}else{
return false;
}
}
return false;
}
};
运行结果