标签:right TreeNode val 572 Tree tree return LeetCode left
Given the roots of two binary trees root
and subRoot
, return true
if there is a subtree of root
with the same structure and node values of subRoot
and false
otherwise.
A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considered as a subtree of itself.
Solution
我们可以递归地去 \(check\) 针对每一个节点,遍历每一个节点我们使用 \(BFS\) 即可
点击查看代码
/**
* 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 {
private:
bool check(TreeNode* s, TreeNode* t){
if(!s && !t)return true;
if(!s || !t)return false;
if(s->val == t->val)
return check(s->left, t->left) && check(s->right, t->right);
else return false;
}
public:
bool isSubtree(TreeNode* root, TreeNode* subRoot) {
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
auto f = q.front(); q.pop();
if(check(f, subRoot))return true;
if(f->left)q.push(f->left);
if(f->right)q.push(f->right);
}
return false;
}
};
标签:right,TreeNode,val,572,Tree,tree,return,LeetCode,left 来源: https://www.cnblogs.com/xinyu04/p/16549330.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。