题目链接: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); } };