递归:
本题可在相同的树的基础上稍作改动
/**
* 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 compare(TreeNode* left,TreeNode* right){
//空结点情况
if(left == NULL && right != NULL){
return false;
}else if(right == NULL && left != NULL){
return false;
}else if(left == NULL && right == NULL){
return true;
}else if(left->val != right->val){
//数值不同的情况
return false;
}
//左右节点都不为空 且数值相同
bool outside = compare(left->left,right->left);
bool inside = compare(left->right,right->right);
bool result = outside && inside;
return result;
}
bool isSubtree(TreeNode* root, TreeNode* subRoot) {
//将root树的每一个子树与其比较
queue<TreeNode*> que;
que.push(root);
while(!que.empty()){
int size = que.size();
for(int i = 0;i<size;i++){
TreeNode *node = que.front();
que.pop();
if(node->val == subRoot->val){
bool result = compare(node,subRoot);
if(result){
return result;
}
}
if(node->left){
que.push(node->left);
}
if(node->right){
que.push(node->right);
}
}
}
return false;
}
};
迭代:仅compare内容与递归不同
class Solution {
public:
//比较两棵树是否相同
bool compare(TreeNode* p,TreeNode* q){
if (p == NULL && q == NULL){
return true;
}
if (p == NULL || q == NULL){
return false;
}
//迭代
queue<TreeNode*> que;
//根节点入队
que.push(p);
que.push(q);
//遍历
while(!que.empty()){
TreeNode* cur1 = que.front();
que.pop();
TreeNode* cur2 = que.front();
que.pop();
//两节点都为空
if(cur1== NULL && cur2 == NULL){
continue;
}
//某一节点为空或者两节点不为空时数值不一样
if(!cur1 || !cur2 || cur1->val != cur2->val){
return false;
}
//将该结点的左右孩子结点加入
que.push(cur1->left);
que.push(cur2->left);
que.push(cur1->right);
que.push(cur2->right);
}
return true;
}
bool isSubtree(TreeNode* root, TreeNode* subRoot) {
//将root树的每一个子树与其比较
queue<TreeNode*> que;
que.push(root);
while(!que.empty()){
int size = que.size();
for(int i = 0;i<size;i++){
TreeNode *node = que.front();
que.pop();
if(node->val == subRoot->val){
bool result = compare(node,subRoot);
if(result){
return result;
}
}
if(node->left){
que.push(node->left);
}
if(node->right){
que.push(node->right);
}
}
}
return false;
}
};