题目:
思路:
深度优先搜索,遍历root的每一个节点代表的整棵树是否和subroot一样。比较是否一样的时候可以从根节点开始递归,首先查看是否为空,然后值是否一样。
代码:
vs可运行代码:
(要定义一下二叉树节点)
#include <iostream>
#include<vector>
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:bool check(TreeNode *s, TreeNode *t) {//两者空 Tif (!s && !t) {return true;}//其中一个空 F//root值不一样 Fif (!s || !t || s->val != t->val) {return false;}//return 递归 s的左和t的左 && s的右和t的右return check(s->left, t->left) && check(s->right, t->right);}bool dfs(TreeNode *s, TreeNode *t) {return check(s, t) || dfs(s->left, t) || dfs(s->right, t);}bool isSubtree(TreeNode *s, TreeNode *t) {return dfs(s, t);}
};// 辅助函数:创建二叉树
TreeNode* createTree(vector<int>& values, int index) {if (index >= values.size() || values[index] == -1) {return nullptr;}TreeNode* root = new TreeNode(values[index]);root->left = createTree(values, 2 * index + 1);root->right = createTree(values, 2 * index + 2);return root;
}// 辅助函数:删除二叉树
void deleteTree(TreeNode* root) {if (root) {deleteTree(root->left);deleteTree(root->right);delete root;}
}int main() {// 创建示例树vector<int> rootValues = { 3, 4, 5, 1, 2 }; // 这里使用-1表示空节点vector<int> subRootValues = { 4, 1, 2 };TreeNode* root = createTree(rootValues, 0);TreeNode* subRoot = createTree(subRootValues, 0);Solution sol;bool result = sol.isSubtree(root, subRoot);cout << "Is subRoot a subtree of root? " << (result ? "Yes" : "No") << endl;// 清理内存deleteTree(root);deleteTree(subRoot);return 0;
}
力扣代码:
class Solution {
public:bool check(TreeNode *o, TreeNode *t) {if (!o && !t) {return true;}if ((o && !t) || (!o && t) || (o->val != t->val)) {return false;}return check(o->left, t->left) && check(o->right, t->right);}bool dfs(TreeNode *o, TreeNode *t) {if (!o) {return false;}return check(o, t) || dfs(o->left, t) || dfs(o->right, t);}bool isSubtree(TreeNode *s, TreeNode *t) {return dfs(s, t);}
};
小结:感觉今天和lhw交流他说的很有道理,LeetCode的每日一题可以当作学习使用(不需要绞尽脑汁去费劲想,思考一下思路直接看题解);而LeetCode100题是循序渐进的过程。
所以决定接下来的日子里,主攻100题,每日一题当作放松!