题解|#判断t1树中是否有与t2树完全相同的子树#|C++
判断t1树中是否有与t2树完全相同的子树
https://www.nowcoder.com/practice/4eaccec5ee8f4fe8a4309463b807a542
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ class Solution { bool dfs(TreeNode* tree1, TreeNode* tree2) { if (tree1 == nullptr && tree2 == nullptr) return true; if (tree1 == nullptr || tree2 == nullptr) return false; if (tree1->val != tree2->val) return false; return dfs(tree1->left, tree2->left) && dfs(tree1->right, tree2->right); } public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root1 TreeNode类 * @param root2 TreeNode类 * @return bool布尔型 */ bool isContains(TreeNode* root1, TreeNode* root2) { if (root1 == nullptr && root2 == nullptr) return true; if (root1 == nullptr || root2 == nullptr) return false; if (dfs(root1, root2)) return true; return isContains(root1->left, root2) || isContains(root1->right, root2); } };