{ "type": "code_options", "author": "https://github.com/begeekmyfriend/leetcode", "source": "solution.md", "exercise_id": "3dab732122934bb1b85db4da70e5f921", "keywords": "树,深度优先搜索,广度优先搜索,二叉树", "title": "相同的树", "desc": [ { "content": "\n

给你两棵二叉树的根节点 pq ,编写一个函数来检验这两棵树是否相同。

如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

 

示例 1:

\"\"
输入:p = [1,2,3], q = [1,2,3]
输出:
true

示例 2:

\"\"
输入:p = [1,2], q = [1,null,2]
输出:
false

示例 3:

\"\"
输入:p = [1,2,1], q = [1,1,2]
输出:
false

 

提示:

", "language": "markdown" } ], "answer": [ { "content": "", "language": "cpp" } ], "prepared": [ [ { "content": "", "language": "cpp" } ], [ { "content": "", "language": "cpp" } ], [ { "content": "", "language": "cpp" } ] ], "template": { "content": "#include \nusing namespace std;\nstruct TreeNode\n{\n\tint val;\n\tTreeNode *left;\n\tTreeNode *right;\n\tTreeNode() : val(0), left(nullptr), right(nullptr) {}\n\tTreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n\tTreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n};\nclass Solution\n{\npublic:\n\tbool isSameTree(TreeNode *p, TreeNode *q)\n\t{\n\t\tif (p == nullptr && q == nullptr)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\tif (p == nullptr || q == nullptr)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\tif (p->val != q->val)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\treturn isSameTree(p->left, q->left) && isSameTree(p->right, q->right);\n\t}\n};", "language": "cpp" }, "node_id": "dailycode-23f90fd7082f4f6ab37a2f1df0d084d8", "license": "csdn.net", "created_at": 1637894160, "topic_link": "https://bbs.csdn.net/topics/600469927" }