力扣-572题 另一棵树的子树(C++)- 递归+有价值+有100题的思路
作者:互联网
题目链接:https://leetcode-cn.com/problems/subtree-of-another-tree/
题目如下:
/**
* 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 isSubtree(TreeNode* root, TreeNode* subRoot) {
//遍历完s,还没匹配到,则返回false
if(root==NULL) return false;
//短路运算符,有一个为真,则返回真
return dfs(root,subRoot)||isSubtree(root->left,subRoot)||isSubtree(root->right,subRoot);
}
//此函数为判断两个子树是否相同的函数,同力扣第100题
bool dfs(TreeNode* p1,TreeNode* p2){
if(p1==NULL&&p2==NULL) return true;
if(p1==NULL&&p2!=NULL) return false;
if(p1!=NULL&&p2==NULL) return false;
if(p1->val!=p2->val) return false;
return dfs(p1->left,p2->left)&&dfs(p1->right,p2->right);
}
};
标签:right,TreeNode,572,C++,力扣,p1,return,NULL,left 来源: https://blog.csdn.net/qq_40467670/article/details/120630918