# 相同的树
给你两棵二叉树的根节点 p
和 q
,编写一个函数来检验这两棵树是否相同。
如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
示例 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
提示:
- 两棵树上的节点数目都在范围
[0, 100]
内 -104 <= Node.val <= 104
以下错误的选项是?
## aop
### before
```cpp
#include
using namespace std;
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) {}
};
```
### after
```cpp
```
## 答案
```cpp
都是错的
```
## 选项
### A
```cpp
class Solution
{
public:
bool isSameTree(TreeNode *p, TreeNode *q)
{
if (p == nullptr)
return q == nullptr;
return q != nullptr && p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
};
```
### B
```cpp
class Solution
{
public:
bool isSameTree(TreeNode *p, TreeNode *q)
{
TreeNode *temp, *temq;
temp = p;
temq = q;
bool lb, rb;
if (!p && !q)
return true;
if ((!p || !q) || p->val != q->val)
return false;
else
{
lb = isSameTree(p->left, q->left);
rb = isSameTree(p->right, q->right);
}
if (lb && rb)
return true;
else
return false;
}
};
```
### C
```cpp
class Solution
{
public:
bool isSameTree(TreeNode *p, TreeNode *q)
{
if (p == NULL && q == NULL)
return true;
if (p == NULL || q == NULL)
return false;
if (p->val != q->val)
return false;
return (isSameTree(p->left, q->left) && isSameTree(p->right, q->right));
}
};
```