给你两棵二叉树 root 和 subRoot 。检验 root 中是否包含和 subRoot 具有相同结构和节点值的子树。如果存在,返回 true ;否则,返回 false 。
二叉树 tree 的一棵子树包括 tree 的某个节点和这个节点的所有后代节点。tree 也可以看做它自身的一棵子树。
示例 1:
输入:root = [3,4,5,1,2], subRoot = [4,1,2] 输出:true 示例 2:
输入:root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2] 输出:false
提示:
root 树上的节点数量范围是 [1, 2000] subRoot 树上的节点数量范围是 [1, 1000] -104 <= root.val <= 104 -104 <= subRoot.val <= 104 通过次数115,674提交次数243,636 请问您在哪类招聘中遇到此题?
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/subtree-of-another-tree 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public:
bool isSubtree(TreeNode* root, TreeNode* subRoot) {
if(!root&&!subRoot)return true;
if(!root||!subRoot)return false;
if(isSameTree(root,subRoot))return true;
bool a = isSubtree(root->left,subRoot);
bool b = isSubtree(root->right,subRoot);
bool c = (a||b);
return c;
}
bool isSameTree(TreeNode*root,TreeNode*subRoot)
{
if(!root&&!subRoot)return true;
if(!root||!subRoot)return false;
if(root->val!=subRoot->val)return false;
bool a = isSameTree(root->left,subRoot->left);
bool b = isSameTree(root->right,subRoot->right);
bool c = (a&&b);
return c;
}
};
class Solution {
public:
bool isSubtree(TreeNode* root, TreeNode* subRoot) {
queue<TreeNode*>qu;
qu.push(root);
while(!qu.empty())
{
TreeNode* Node = qu.front();
qu.pop();
bool a = isSameTree(Node,subRoot);
if(a)
{
return true;
}
if(Node->left)qu.push(Node->left);
if(Node->right)qu.push(Node->right);
}
return false;
}
bool isSameTree(TreeNode*root,TreeNode*subRoot)
{
queue<TreeNode*>qu1;
qu1.push(root);
qu1.push(subRoot);
while(!qu1.empty())
{
TreeNode* Node1 = qu1.front();
qu1.pop();
TreeNode* Node2 = qu1.front();
qu1.pop();
if(!Node1&&!Node2)continue;
if(!Node1||!Node2||(Node1->val!=Node2->val))return false;
qu1.push(Node1->left);
qu1.push(Node2->left);
qu1.push(Node1->right);
qu1.push(Node2->right);
}
return true;
}
};
class Solution {
public:
bool isSubtree(TreeNode* root, TreeNode* subRoot) {
stack<TreeNode*>qu;
qu.push(root);
while(!qu.empty())
{
TreeNode* Node = qu.top();
qu.pop();
bool a = isSameTree(Node,subRoot);
if(a)
{
return true;
}
if(Node->left)qu.push(Node->left);
if(Node->right)qu.push(Node->right);
}
return false;
}
bool isSameTree(TreeNode*root,TreeNode*subRoot)
{
stack<TreeNode*>qu1;
qu1.push(root);
qu1.push(subRoot);
while(!qu1.empty())
{
TreeNode* Node1 = qu1.top();
qu1.pop();
TreeNode* Node2 = qu1.top();
qu1.pop();
if(!Node1&&!Node2)continue;
if(!Node1||!Node2||(Node1->val!=Node2->val))return false;
qu1.push(Node1->left);
qu1.push(Node2->left);
qu1.push(Node1->right);
qu1.push(Node2->right);
}
return true;
}
};
|