代码解决
/*** 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 isSameTree(TreeNode* p, TreeNode* q) {if (p == nullptr && q == nullptr) {return true;} else if (p == nullptr || q == nullptr) {return false;}queue<TreeNode*> que1;if(p!=nullptr) que1.push(p);queue<TreeNode*> que2;if(q!=nullptr) que2.push(q);while(!que1.empty()&&!que2.empty()){auto node1=que1.front();que1.pop();auto node2=que2.front();que2.pop();if(node1->val!=node2->val){return false;}auto left1=node1->left,right1=node1->right,left2=node2->left,right2=node2->right;if ((left1 == nullptr) ^ (left2 == nullptr)) {return false;}if ((right1 == nullptr) ^ (right2 == nullptr)) {return false;}if (left1 != nullptr) {que1.push(left1);}if (right1 != nullptr) {que1.push(right1);}if (left2 != nullptr) {que2.push(left2);}if (right2 != nullptr) {que2.push(right2);}}return que1.empty()&&que2.empty();}
};
代码解决2
/*** 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 isSameTree(TreeNode* p, TreeNode* q) {// 如果两个节点都为空,则它们相同if(p==nullptr&&q==nullptr){return true;}// 如果只有一个节点为空,则它们不同else if(p==nullptr||q==nullptr){return false;}// 如果两个节点的值不同,则它们不同else if(p->val!=q->val){return false;}// 递归地比较左子树和右子树else{return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);}}
};