题目.jpg
题目.jpg
题目.jpg
题目.jpg
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <algorithm>
using namespace std;
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:
// 1.确定递归函数入参及返回值
bool compare(TreeNode* tr1, TreeNode* tr2) {
// 2.确定函数的递归终止条件
if(tr1 == nullptr && tr2 == nullptr) return true;
else if(tr1 == nullptr && tr2 != nullptr) return false;
else if(tr1 != nullptr && tr2 == nullptr) return false;
else if(tr1->val != tr2->val) return false;
// 3.确定单层递归逻辑
else return compare(tr1->left, tr2->left) && compare(tr1->right, tr2->right);
}
bool isSubTree(TreeNode* root, TreeNode* subRoot) {
if(root == nullptr) return false;
if(subRoot == nullptr) return true;
// 符合subRoot是root子树的三种情况(满足其中之一即可):两棵树完全相同;SubRoot为root的左子树;SubRoot为root的右子树
return compare(root, subRoot) || isSubTree(root->left, subRoot) || isSubTree(root->right, subRoot);
}
};
网友评论